1.__str__
class Student (object): def __init__ (self, name): == Student ("Michael")print m
<__main__. Student Object at 0x0000000003280ef0>
To make the result format of the print class easier to read
Rewrite __str__ (self)
class Student (object): def __init__ (self, name): = name def__str__(self): return" Student Name is%s! "%= Student ("Michael")print m
is Michael!
__repr__ similar to __str__, different __repr__ mainly use the interaction with the developer
2.__iter__
To change a class to an iterative type
classFib (object):def __init__(self): SELF.A=0 self.b= 1def __iter__(self):return SelfdefNext (self): SELF.A, self.b= self.b, SELF.A +self.bifSELF.A > 100: Raisestopiteration ()returnSELF.A forNinchFib ():PrintN
3.__getitem__
For iterations, you can use array subscripts to access the variables
classFib (object):def __init__(self): SELF.A=0 self.b= 1def __iter__(self):return SelfdefNext (self): SELF.A, self.b= self.b, SELF.A +self.bifSELF.A > 100: Raisestopiteration ()returnSELF.Adef __getitem__(self, item): forIinchRange (item): SELF.A, self.b= self.b, SELF.A +self.breturnSELF.APrintFib () [11]
4.__getattr__
Directly on the example:
classPerson (object):def __init__(self): Self.name="Michael" def __getattr__(self, item):ifitem = =" Age": Self.age= 22returnSelf.agem=Person ()PrintM.__getattr__(" Age")
Attach a code that dynamically generates a path
classClain (object):def __init__(Self, path=""): Self._path=Pathdef __getattr__(self, item):returnClain ("%s/%s"%(Self._path, item))def __str__(self):returnSelf._pathPrintClain (). Usr.bin.env.python
/usr/bin/env/python
5.__call__
Invoking instances directly
Last Example:
class Person (object): def __init__ (self): " Michael " def __call__ (Self, *args, * *Kwargs) : Print " My name is%s " % self.name = Person () m ()
is Michael
Attached: __getattr__ and __call__ Federated calls
classClain (object):def __init__(Self, path=""): Self._path=Pathdef __getattr__(self, item):returnClain ("%s/%s"%(Self._path, item))def __str__(self):returnSelf._pathdef __call__(Self, *args, * *Kwargs): forIinchArgs:self._path="%s/%s"%(Self._path, i)returnClain (Self._path)PrintClain (). USR ("Michael"). Bin.env.python
/usr/michael/bin/env/python
Python Custom class