Python Object-oriented
Python has been an object-oriented language since its inception, which is why it is easy to create a class and object in Python. In this section we will detail Python's object-oriented programming.
If you have not been exposed to object-oriented programming languages before, you may need to first understand some of the basic features of object-oriented languages and form a basic object-oriented concept in your mind, which will help you learn more about Python's object-oriented programming.
Let's start with a brief look at some of the basic features of object-oriented.
Introduction to Object-oriented technology
- class: used to describe a collection of objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection. An object is an instance of a class .
- Class variables: class variables are common throughout the instantiated object. Class variables are defined in the class and outside the body of the function. Class variables are not typically used as instance variables.
- data members: class variables or instance variables are used to manipulate the data related to the class and its instance objects.
- method Overrides: if the method inherited from the parent class does not meet the requirements of the subclass, it can be overridden, which is called the override of the method, also known as the override of the method.
- instance variable: A variable defined in a method that acts only on the class of the current instance.
- inheritance: A derived class (derived class) that inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is a design where an object of type dog is derived from the animal class, which is the analog "is a (is-a)" Relationship (example, dog is a animal).
- instantiation: Creates an instance of a class, the concrete object of the class.
- method: a function defined in a class.
- object: An instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.
Create Class
Use the class statement to create a new class, followed by the name of the class and ending with a colon, as in the following example:
Class ClassName: ' Help information for classes ' #类文档字符串 class_suite #类体
The Help information for the class can be viewed through classname.__doc__.
Class_suite consists of class members, methods, and data properties.
Instance
Here is a simple example of a Python class:
#!/usr/bin/python#-*-coding:utf-8-*-class Employee: ' base class for all employees ' 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, ", Sala Ry: ", self.salary
- The Empcount variable is a class variable whose value is shared among all instances of the class. You can use Employee.empcount access in internal classes or outside classes.
- The first method, the __init__ () method, is a special method called the constructor or initialization method of a class that is called when an instance of the class is created.
Creating an Instance Object
To create an instance of a class, you can use the name of the class and accept the arguments through the __init__ method.
"Create first object of Employee class" EMP1 = Employee ("Zara", 2000) "Create second object of employee class" EMP2 = Employee ("Manni", 5000)
Accessing properties
You can use the dot (.) To access the properties of the object. Access the class variable using the name of the following class:
Emp1.displayemployee () Emp2.displayemployee () print "Total Employee%d"% Employee.empcount
Complete Example:
#!/usr/bin/python#-*-coding:utf-8-*-class Employee: ' base class for all employees ' 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, ", Sala Ry: ", self.salary" creates the first object of the employee class "EMP1 = Employee (" Zara ", 2000)" creates the second object of the employee class "EMP2 = Employee (" Manni "," the "x) EMP 1.displayEmployee () Emp2.displayemployee () print "Total Employee%d"% Employee.empcount
Execute the above code to output the result as follows:
Name: Zara, Salary: 2000Name: Manni, Salary: 5000Total Employee 2
You can add, remove, and modify the properties of the class as follows:
Emp1.age = 7 # Add an ' age ' property Emp1.age = 8 # modify ' Age ' property del emp1.age # delete ' age ' property
You can also access properties by using the following functions:
- GetAttr (obj, name[, default]): Accesses the properties of the object.
- Hasattr (obj,name): Checks if a property exists.
- SetAttr (Obj,name,value): Sets a property. If the property does not exist, a new property is created.
- Delattr (obj, name): Deletes the attribute.
Hasattr (EMP1, ' age ') # returns True if the ' age ' property exists. GetAttr (EMP1, ' age ') # Returns the value of ' age ' property setattr (EMP1, ' age ', 8) # Add attribute ' age ' value to 8delattr (Empl, ' age ') # Delete attribute ' age '
Python built-in class properties
- __DICT__: Properties of the Class (contains a dictionary, consisting of the data properties of the Class)
- __DOC__: Document string for Class
- __NAME__: Class name
- __MODULE__: The module where the class definition resides (the full name of the class is ' __main__.classname ', if the class is in an import module mymod, then classname.__module__ equals Mymod)
- __BASES__: All parent classes of a class make up elements that contain a tuple of all the parent classes
The python built-in class property invocation instance is as follows:
#!/usr/bin/python#-*-coding:utf-8-*-class Employee: ' base class for all employees ' 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, ", Sal ary: ", 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__
Execute the above code to output the result as follows:
EMPLOYEE.__DOC__: base class for all employees employee.__name__: employeeemployee.__module__: __main__employee.__bases__: () Employee.__ dict__: {' __module__ ': ' __main__ ', ' displaycount ': <function displaycount at 0x10a939c80>, ' Empcount ': 0, ' Displayemployee ': <function displayemployee at 0x10a93caa0>, ' __doc__ ': ' \xe6\x89\x80\xe6\x9c\x89\xe5\x91\x98\ Xe5\xb7\xa5\xe7\x9a\x84\xe5\x9f\xba\xe7\xb1\xbb ', ' __init__ ': <function __init__ at 0x10a939578>}
Python Object Destruction (garbage collection)
Python uses the simple technique of reference counting to track and recycle garbage.
Inside Python is a record of how many references each object in use has.
An internal tracking variable, called a reference counter.
When the object is created, a reference count is created, and when the object is no longer needed, that is, the reference count of the object becomes 0 o'clock, and it is garbage collected. However, recycling is not "immediate", and the interpreter uses the garbage object to reclaim the memory space at the appropriate time.
A = + # Create object <40>b = A # Add reference, <40> count C = [b] # Add Reference. <40> Count del a # reduce the count of references <40> B = # # Reduce the reference <40> count c[0] =-1 # Reduce the count of references <40>
The garbage collection mechanism not only targets objects with a reference count of 0, but can also handle circular references. Circular references refer to two of objects referencing each other, but no other variables refer to them. In this case, using only the reference count is not enough. The Python garbage collector is actually a reference counter and a cyclic garbage collector. As a supplement to the reference count, the garbage collector also pays attention to objects that are allocated a large amount (and those that are not destroyed by reference counting). In this case, the interpreter pauses to attempt to clean up all unreferenced loops.
Instance
destructor __del__, __del__ is called when the object is destroyed, and the __del__ method runs when the object is no longer being used:
#!/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 = pt1 Print ID (PT1), id (PT2), id (PT3) # Prints the object's Iddel Pt1del Pt2del PT3
The results of the above example operation are as follows:
3083401324 3083401324 3083401324Point Destruction
Note: typically you need to define a class in a separate file,
Inheritance of Classes
One of the main benefits of object-oriented programming is the reuse of code, and one way to implement this reuse is through inheritance mechanisms. Inheritance can be fully understood as a type and subtype relationship between classes.
What to note: Inherit the syntax class derived class name ( base class name )://... The base class name is written in parentheses, and the base class is specified in the tuple at the time the class is defined.
Some of the characteristics of inheritance in Python:
- 1: The construction of the base class in inheritance (The __init__ () method) is not automatically called, it needs to be called specifically in the construction of its derived class.
- 2: When calling a method of the base class, you need to prefix the class name of the base class with the Self argument variable. Unlike calling a normal function in a class, you do not need to take the self argument
- 3:python always looks for a method of the corresponding type first, and if it cannot find the corresponding method in the derived class, it begins to look in the base class one by one. (Find the method that was called in this class before you can find it in the base class).
If more than one class is listed in an inheritance tuple, it is called "Multiple inheritance."
Grammar:
The declarations of derived classes, like their parent class, inherit the list of base classes followed by the class name, as follows:
Class Subclassname (parentclass1[, ParentClass2, ...]): ' Optional class documentation string ' Class_suite
Instance:
#!/usr/bin/python#-*-coding:utf-8-*-class Parent: # defines the parental class parentattr = def __init__ (self): print "Call parent class constructor" def Parentmethod (self): print ' calls the parent class method ' def setAttr (self, attr): parent.parentattr = attr def getAttr (self): print "Parent class Property:", Parent.parentattrclass Child (Parent): # defines the subclass def __init__ (self): print "Call subclass constructor Method" def Childmethod (self): print ' call subclass method ' Child methods ' C = Children () # Instantiate subclass C.childmethod () # Call a method of a subclass C.parentmethod () # Call the parent class method C.setattr (#) # Call the parent class again method C.getattr () # Call a method of the parent class again
The result of the above code execution is as follows:
Call subclass method calls subclass methods Child methods Call Parent class method Parent Class Property: 200
You can inherit multiple classes
Class A: # defines classes A.....class B: # defines classes B.....class C (A, B): # Inherit classes A and B .....
You can use the Issubclass () or Isinstance () method to detect.
- Issubclass ()-Boolean function to determine whether a class is a subclass of another class or descendant class, syntax: Issubclass (SUB,SUP)
- Isinstance (obj, Class) Boolean function returns True if OBJ is an instance object of class or is an instance object of class subclass.
Method overrides
If the functionality of your parent's methods does not meet your needs, you can override the methods of your parent class in subclasses:
Instance:
#!/usr/bin/python#-*-coding:utf-8-*-class Parent: # defines the parents class def myMethod (self): print ' calls the parent class method ' class child ( Parent): # definition Subclass def myMethod (self): print ' call subclass method ' C = Child () # Subclass Instance C.mymethod () # Subclass Call override method
Execute the above code to output the result as follows:
Calling Subclass Methods
Base overloaded methods
The following table lists some of the common features that you can override in your own class:
Serial Number |
method, Description & Simple Call |
1 |
__init__ (self [, args ...]) constructor function Simple invocation method: obj = className (args) |
2 |
__del__ (self) destructor method, deleting an object Simple method of invocation: Dell obj |
3 |
__repr__ (self) Translates into a form for the interpreter to read Simple method of invocation: repr (obj) |
4 |
__str__ (self) Used to convert a value into a form suitable for human reading Simple method of invocation: str (obj) |
5 |
__cmp__ (self, x) Object comparison Simple invocation Method: cmp (obj, x) |
Operator overloading
Python also supports operator overloading with the following examples:
#!/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 + othe r.b) v1 = vector (2,10) v2 = vector (5,-2) Print V1 + v2
Class properties and private properties of method classes
__private_attrs: Two underscores begin with, declaring that the property is private and cannot be used outside of the class or accessed directly. self.__private_attrswhen used in methods inside a class.
Methods of the class
Inside the class, using the DEF keyword, you can define a method for a class that differs from a generic function definition, which must contain the parameter self, and is the first argument
Private methods of the class
__private_method: Two underscores, declares that the method is a private method and cannot be called outside of a class. Calling Self.__private_methods inside a 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 + = 1print Self.__secretcountcounter = Justcounter () counter.count () Counter.count () print counter.publiccountprint counter.__secretcount # Error, instance cannot access private variable
Python includes the class name by changing its name:
122Traceback (most recent): File "test.py", line <module> print Counter.__secretcount # Error, instance cannot access 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 properties and replace the following code with the last line of code:
.......... print Counter._justcounter__secretcount (.....)
Execute the above code and execute the result as follows:
1222
Python Object-oriented class (2)