The previous blog simply said the basic knowledge of the class, the following emphasis on some of the methods commonly used in the class. An obvious sign of the so-called magic method is that the method name is contained by the _ two underscore.
(1) _init_
If you do not overload or override this method, the system will automatically invoke the default Init method, and if you override the method to satisfy your needs, the method you override will automatically override the system's default method.
Class ball: def __init__ (self,name): self.name=name def Kick (self): print ("My name is%s, damn it, who kicked me ...") Self.name) a=ball ("Potato") a.kick ()
After rewriting the Init method itself, we can fill in a parameter when instantiating an object.
Class Rectangle: def __init__ (self,x,y): self.x=x self.y=y def getperi (self): return (self.x+ SELF.Y) * * def getarea (self): return self.x * self.yrect=rectangle (3,4) print (Rect.getarea ()) Print ( Rect.getperi ())
(2) New (two underline before and after)
This method is called before the Init method and is not normally used, so there is no redundancy here.
(3) Del (with two underscores before and after)
Role: Deleting objects
Class C: def __init__ (self): print ("I am the __init__ method, I am called") def __del__ (self): print ("I am the __del__ method, I was called ") c1=c () C2=c1c3=c2del C3del C2del C1
It is important to note that the garbage collection mechanism is only called when all the tags that point to C1 are deleted
Here are a few common magical methods that will be added later on.
The above is the content of the Magic method in the basic primer 13 of Python 0, for more information please follow topic.alibabacloud.com (www.php.cn)!