I have a Python object which has certain attributes that are set after the constructor is called. For example,
def Student(object):
def __init__(name, address=None):
self.name = name
self.address = address
stud = Student("John")
stud.address = "123 Main St. New York, NY"
I would like to be able to have a function be called when the address attribute is set which will do things such as reformat the address or do a lookup and add in the zip code, etc. Is there a way to accomplish this within the object's definition or should I just have to do that myself every time I set the address attribute?
What you probably need is a property concept.
class C(object):
def __init__(self, x):
self._x = x
def get_x(self):
return self._x
def set_x(self, x):
self._x = x
x = property(get_x, set_x)
obj = C(5)
obj.x = 6 # set
print obj.x # get
See this link for more details: http://snippets.dzone.com/posts/show/954
You're looking for property().
def Student(object):
def _get_address(self):
...
def _set_address(self):
...
address = property(_get_address, _set_address)
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