予約語property
を使用している神を捨て去った神があります。間違っています。継承される基本クラスでは、基本的に実装されています。プロパティ予約語の誤用
class TestClass(object):
def __init__(self, property):
self._property = property
@property
def property(self):
return self._property
test = TestClass('test property')
print(test.property)
エラーなく実行されます。
---> 10 @property
11 def other_property(self):
12 print('test other property')
TypeError: 'property' object is not callable
をあなたはローカル名前空間内property
を上書きしている知っているので:あなたはその下に別のメソッドを追加する場合は、スロー
class TestClass2(object):
def __init__(self, property):
self._property = property
@property
def property(self):
return self._property
@property
def other_property(self):
return 'test other property'
test = TestClass2('test property')
print(test.property)
print(test.other_property)
を取得します。
class TestClass3(object):
def __init__(self, property):
self._property = property
@property
def other_property(self):
return 'test other property'
@property
def property(self):
return self._property
test = TestClass3('test property')
print(test.property)
print(test.other_property)
あなたは常にあなたのクラスの一番下にあなたのproperty
上書きを定義する場合は、これを回避することができます。 property
メソッドが基底クラスでのみ定義されている場合は、名前空間を使用するため、継承したものからも機能します。
class TestClass4(TestClass):
def __init__(self, property):
super(TestClass4, self).__init__(property)
@property
def other_property(self):
return 'test other property'
test = TestClass4('test property')
print(test.property)
print(test.other_property)
私の義憤はほとんど変更されていないベースでproperty
定義の定義の上に新しいメソッドを追加することを忘れないように持つ以外の理由GAAAAHが、我々は、レガシーコードの膨大な量で、この変数名を更新しなければならないと述べていますこれは実際に何かを壊すことはありませんか?
downvoter reason?私はdownvoteと私は好きですが、私は好奇心がなぜですか? –
プロパティを使用する理由はたくさんあります。アクセサーやミューテータの代わりに属性を使ってapiを公開するのは非常に難しいですが、それはあなたが値を遅く計算できなかったり、人々が値を設定したときに副作用があったりすることを意味します。 'property'はあなたが両方の世界のベストを持つことを可能にします。 –
Pythonにプライベート変数がありません...と私は言ったすべての意見だった私は確かにプロパティを使用して彼を止めていない...私の意見は、私の答えには無関係ですimhoは質問に正しい答えです。 –