Reputation: 5206
I have the following code :
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
This should work (see here). However, it is not and my questions are as follows :
c.dx = 42
?Upvotes: 1
Views: 2547
Reputation: 10447
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
Source: http://docs.python.org/tutorial/classes.html#private-variables
Upvotes: 0
Reputation: 129764
property
with no setter defined is read-only. The only reason this might not work is that you're using Python 2 and defined an old-style class. Remember to always derive from object
in Python 2.x:
class C(object):
@property
def dx(self):
return self._dx
def __init__(self, dx = 1):
self._dx = dx
Upvotes: 4