_ Bases _: Elements of all parent classes of the class (including tuples consisting of all parent classes)
The Python built-in class property call example is as follows:
#! /Usr/bin/python #-*-coding: UTF-8-*-class Employee: 'All employees' base classes 'empcount = 0 def _ init _ (self, name, salary): self. name = name self. salary = salary Employee. empCount + = 1 def displayCount (self): print "Total Employee % d" % Employee. empCount def displayEmployee (self): print "Name:", self. name, ", Salary:", self. salaryprint "Employee. _ doc __: ", Employee. _ doc _ print "Employee. _ name __: ", Employee. _ name _ print "Employee. _ module __: ", Employee. _ module _ print "Employee. _ bases __: ", Employee. _ bases _ print "Employee. _ dict __: ", Employee. _ dict __
The output result is as follows:
Employee. _ doc __: the base class of all employees. _ name __: EmployeeEmployee. _ module __: _ main _ Employee. _ bases __: () Employee. _ dict __:{ '_ module _': '_ main _', 'displaycount ':
, 'Empcount': 0, 'displayemployee ':
, '_ Doc __': '\ xe6 \ x89 \ x80 \ xe6 \ x9c \ x89 \ xe5 \ x91 \ x98 \ xe5 \ xb7 \ xa5 \ xe7 \ x9a \ x84 \ xe5 \ x9f \ xba \ xe7 \ xb1 \ xbb ', '_ init __':
}
Python object destruction (garbage collection)
Like the Java language, Python uses the reference count simple technology to track objects in memory.
In Python, the number of references of all objects in use is recorded.
An internal trace variable is called a reference counter.
When an object is created, a reference count is created. When this object is no longer needed, that is, when the reference count of this object is changed to 0, it is recycled. However, the recycle object is not "immediate". At the right time, the interpreter recycles the memory space occupied by the spam object.
A = 40 # create an object <40> B = a # Add reference, <40> Count c = [B] # Add reference. <40> count del a # reduce reference <40> Count B = 100 # reduce reference <40> Count c [0] =-1 # reduce reference <40> count
The garbage collection mechanism is applicable not only to objects with 0 reference counts, but also to circular references. Loop Reference refers to the mutual reference between two objects, but no other variables reference them. In this case, it is not enough to use only the reference count. The Python garbage collector is actually a reference counter and a circular garbage collector. As a supplement to reference counting, the garbage collector will also pay attention to objects with a large total allocation volume (and those that are not destroyed by reference counting. In this case, the interpreter pauses and tries to clear all the loops that are not referenced.
Instance
The Destructor _ del _ ,__ del _ is called when the object is destroyed. When the object is no longer used, run the __del _ method:
#! /Usr/bin/python #-*-coding: UTF-8-*-class Point: def _ init _ (self, x = 0, y = 0): self. x = x self. y = y def _ del _ (self): class_name = self. _ class __. _ name _ print class_name, "Destroy" pt1 = Point () pt2 = pt1pt3 = pt1print id (pt1), id (pt2), id (pt3) # print the iddel pt1del pt2del pt3 of the object
The running result of the above instance is as follows:
3083401324 3083401324 3083401324 Point destruction
Note: You usually need to define a class in a separate file,
Class inheritance
One of the main benefits of object-oriented programming is code reuse. One of the ways to achieve this reuse is through the inheritance mechanism. Inheritance can be fully understood as the relationship between types and subtypes between classes.
Note: inherited syntax class derived class name (base class name )://... in the base class name writing brackets, the basic class is specified in the tuples when the class is defined.
Some features of inheritance in python:
- 1: The Construction (_ init _ () method) of the base class in the inheritance class will not be automatically called. It needs to be called in the construction of its derived class.
- 2: when calling a base class method, you must add the base class name prefix and the self parameter variable. Unlike calling a common function in a class, the self parameter is not required.
- 3: Python always first looks for the corresponding type of method. If it cannot find the corresponding method in the derived class, it starts to look for it one by one in the base class. (Search for the called method in this class before finding it in the base class ).
If more than one class is listed in the inheritance tuples, it is called "Multi-inheritance ".
Syntax:
The declaration of a derived class is similar to that of its parent class. The list of inherited base classes follows the class name, as shown below:
class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite
Instance:
#! /Usr/bin/python #-*-coding: UTF-8-*-class Parent: # define Parent class parentAttr = 100 def _ init _ (self ): print "calling the Parent class constructor" def parentMethod (self): print 'Call the Parent class method' def setAttr (self, attr): Parent. parentAttr = attr def getAttr (self): print "Parent class property:", Parent. parentAttrclass Child (Parent): # define the subclass def _ init _ (self): print "Call the subclass constructor" def childMethod (self ): print 'call subclass method child method' c = Child () # instantiate subclass c. childMethod () # Call The subclass method c. parentMethod () # Call the parent class method c. setAttr (200) # Call the method c of the parent class again. getAttr () # Call the method of the parent class again
The code execution result is as follows:
Call subclass constructor call subclass method child method call parent class method parent class property: 200
You can inherit multiple classes
Class A: # define class ..... class B: # define class B ..... class C (A, B): # inherit classes A and B .....
You can use the issubclass () or isinstance () method for detection.
- Issubclass ()-Boolean function determines whether a class is a subclass or descendant class of another class. Syntax: issubclass (sub, sup)
- The Boolean function of isinstance (obj, Class) returns true if obj is an instance object of the Class or an instance object of a Class subclass. Method Rewriting
If the function of your parent class method cannot meet your needs, you can rewrite the method of your parent class in the subclass:
Instance:
#! /Usr/bin/python #-*-coding: UTF-8-*-class Parent: # define Parent class def myMethod (self ): print 'call Parent class method' class Child (Parent): # define subclass def myMethod (self): print' call subclass method' c = Child () # subclass instance c. myMethod () # subclass calls override method
The output result is as follows:
Call subclass Method
Basic overload method
The following table lists some common functions that can be rewritten in your own class:
| Serial number |
Method, description & simple call |
| 1 |
_ Init _ (self [, args...])
Constructor
Simple call method:Obj = className (args) |
| 2 |
_ Del _ (self)
Structure Method to delete an object
Simple call method:Dell obj |
| 3 |
_ Repr _ (self)
Converted to the form for the interpreter to read
Simple call method:Repr (obj) |
| 4 |
_ Str _ (self)
Used to convert a value into a form suitable for reading.
Simple call method:Str (obj) |
| 5 |
_ Cmp _ (self, x)
Object comparison
Simple call method:Cmp (obj, x) |
Operator overload
Python also supports Operator overloading. The example is as follows:
#!/usr/bin/pythonclass Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b)v1 = Vector(2,10)v2 = Vector(5,-2)print v1 + v2
The code execution result is as follows:
Vector(7,8)
Private attributes of class attributes and method classes
_ Private_attrs: It starts with two underscores and declares that this attribute is private and cannot be used outside the class or accessed directly. Self. _ private_attrs is used in internal methods of the class.
Class Method
Inside the class, you can use the def keyword to define a method for the class. Unlike the general function definition, the class method must contain the self parameter and be the first parameter.
Class private Method
_ Private_method: it must start with an underscore. It is declared as a private method and cannot be called outside the class. Call self. _ private_methods inside the class
Instance
#! /Usr/bin/python #-*-coding: UTF-8-*-class JustCounter :__ secretCount = 0 # private variable publicCount = 0 # public variable def count (self): self. _ secretCount + = 1self. publicCount + = 1 print self. _ secretCountcounter = JustCounter () counter. count () counter. count () print counter. publicCountprint counter. _ secretCount # error: the instance cannot access private variables
Python changes the name to include the Class Name:
122 Traceback (most recent call last): File "test. py", line 17, in
Print counter. _ secretCount # error. The instance cannot access the private variable AttributeError: JustCounter instance has no attribute '_ secretCount'
Python does not allow instantiated classes to access private data, but you can use object. _ className _ attrName to access the attribute and replace the following code with the last line of code of the above Code:
.........................print counter._JustCounter__secretCount
Run the preceding code and the execution result is as follows:
1222