whats the reason to use the variable the self._age? A similar name that doesn't link to the already used self.age?
class newprops(object):
def getage(self):
return 40
def setage(self, value):
self._age = value
age = property(getage, setage, None, None)
self.age
is already occupied by the property, you need to give another name to the actual variable, which is _age
here.
BTW, since Python 2.6, you could write this with decorators:
def newprops(object):
@property
def age(self):
return 40
@age.setter
def age(self, value):
self._age = value
Some object oriented languages have what is called private attributes, which cannot be accessed from outside the class methods. This is important because some attributes are not meant to be changed directly, instead, they are meant to be changed as a function of something else, or validated before they are changed. In Python you don't have private attributes, but you can implement something similar by using getters and setters to a variable which starts with underscore - Python's convention for private methods and attributes.
For instance. The hypotenuse of a rectangular triangle is given by h=sqrt(a*a+b*b)
, so you cannot change h
directly because the relationship must hold. Also, say that a name must me in the format LASTNAME COMMA FIRSTNAME
, then you have to verify that this is the case before you assign self.lastname
.
The property getter allows you to get the hypotenuse, but forbids you from setting it. The property setter allows you to set a property but you can make checks before actually setting the property.
So:
class Person(object)
def __init__(self):
# The actual attribute is _name
self._name = None
@property
def name(self):
# when I ask for the name, I mean to get _name
return self._name
@name.setter
def name(self, value):
# before setting name I can ensure that it has the right format
if regex_name.match(value):
# assume you have a regular expression to check for the name
self._name = value
else:
raise ValueError('invalid name')
Another example:
class Triangle(object):
def __init__(self, a, b):
# here a and b do not need to be private because
# we can change them at will. However, you could
# make them private and ensure that they are floats
# when they are changed
self.a = a
self.b = b
@property
def h(self):
return math.sqrt(a*a+b*b)
# notice there is no h.setter - you cannot set h directly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With