Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Call function if setter is called?

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?

like image 299
john Avatar asked Jul 02 '26 08:07

john


2 Answers

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

like image 158
Dany Avatar answered Jul 04 '26 21:07

Dany


You're looking for property().

def Student(object):
  def _get_address(self):
     ...

  def _set_address(self):
     ...

  address = property(_get_address, _set_address)
like image 32
Ignacio Vazquez-Abrams Avatar answered Jul 04 '26 20:07

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!