我有以下代码:
class C:
def __init__(self, dx = 1):
self._dx = dx
def get_dx(self):
return self._dx
dx = property(get_dx,None,None)
c = C()
print c.dx
c.dx = 42
print c.dx # this shows 42
这应该有效(see here)。但是,它不是,我的问题如下:
c.dx = 42
?答案 0 :(得分:4)
property
是只读的。这可能不起作用的唯一原因是你使用的是Python 2并定义了一个旧式的类。请记住始终派生自Python 2.x中的object
:
class C(object):
@property
def dx(self):
return self._dx
def __init__(self, dx = 1):
self._dx = dx
答案 1 :(得分:0)
class C:
def __init__(self, dx = 1):
self.__dx = dx
def get_dx(self):
return self.__dx
dx = property(get_dx,None,None)
c = C()
print c.get_dx()
print c.__dx # this raise error
来源: http://docs.python.org/tutorial/classes.html#private-variables