propertyを使うときはobjectを継承したクラス (new-style class) を使う

More than 5 years have passed since last update.


new-style classじゃない場合

class Hoge:

def __init__(self):
self._x = 1

@property
def x(self):
print 'property', self._x
return self._x

@x.setter
def x(self, x):
print 'setter'
self._x = x

a = Hoge()
print a.x

a.x = 2
print a.x


結果

property 1

1
2



new-style classの場合

class Hoge(object):

def __init__(self):
self._x = 1

@property
def x(self):
print 'property', self._x
return self._x

@x.setter
def x(self, x):
print 'setter'
self._x = x

a = Hoge()
print a.x

a.x = 2
print a.x


結果

property 1

1
setter
property 2
2


参考