python leading and trailing underscores in user defined functions -
how can used rt function, understand leading & trailing underscores __and__()
available native python objects or wan't customize behavior in specific situations. how can user take advantages of . ex: in below code can use function @ all,
class a(object): def __rt__(self,r): return "yes special functions" a=a() print dir(a) print a.rt('1') # attributeerror: 'a' object has no attribute 'rt'
but
class room(object): def __init__(self): self.people = [] def add(self, person): self.people.append(person) def __len__(self): return len(self.people) room = room() room.add("igor") print len(room) #prints 1
python doesn't translate 1 name another. specific operations under covers call __special_method__
if has been defined. example, __and__
method called python hook &
operator, because python interpreter explicitly looks method , documented how should used.
in other words, calling object.rt()
not translated object.__rt__()
anywhere, not automatically.
note python reserves such names; future versions of python may use name specific purpose , existing code using __special_method__
name own purposes break.
from reserved classes of identifiers section:
__*__
system-defined names. these names defined interpreter , implementation (including standard library). current system names discussed in special method names section , elsewhere. more defined in future versions of python. use of__*__
names, in context, not follow explicitly documented use, subject breakage without warning.
you can ignore advice of course. in case, you'll have write code calls method:
class somebaseclass: def rt(self): """call __rt__ special method""" try: return self.__rt__() except attributeerror: raise typeerror("the object doesn't support operation")
and subclass somebaseclass
.
again, python won't automatically call new methods. still need write such code.
Comments
Post a Comment