#property sample
class blah(object)
def getter(self):
return ...
def setter(self,value):
....
name=property(getter,setter)
inst=blah()
print inst.name #calls inst.getter()
inst.name=23 #like call inst.setter(23)
python special methods (dobleundescore aka dunder):
__new__ __init__ __del__ # ctor,init, finalize
__repr__ __str__ __int__ # convert
__lt__ __gt__ __eq__ # compare
__add__ __sub__ __mul__ # arithmetic
__call__ __hash__ __nonzero__ # ()
__getattr__ __setattr__ __delattr__ #
__getitem__ __setitem__ __delitem__ #
__len__ __iter__ __contains__ #
__get__ __set__ __enter__ __exit__
here's sample of using special methods
class fib(object):
def __init__(self): self.i=self.j=1
def __iter__(self): return self
def next(self):
r,self.i=self.i,self.j
self.j+=r
return r
for r in fib():
print r,
if r > 100: break
1 1 2 3 5 8 13 21 34 55 89 144
more...
No comments:
Post a Comment