classC(object):def__init__(self):self._x=None@propertydefx(self):"""I'm the 'x' property."""print("getter of x called")returnself._x@x.setterdefx(self,value):print("setter of x called")self._x=value@x.deleterdefx(self):print("deleter of x called")delself._xc=C()c.x='foo'# setter calledfoo=c.x# getter calleddelc.x# deleter called
An implementation of this method could be a product where a user can set a price after its instantiation.
classProduct:def__init__(self,name):self._name=name@propertydefprice(self):returnself._price@price.setterdefprice(self,new_price):ifnew_price<0ornotisinstance(new_price,float):raiseException("price must be greater than 0 and a float")self._price=new_price@price.deleterdefprice(self):delself._pricep1=Product("one")p1.price=5.5