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 Overloading: If a method inherited from a parent class does not meet the requirements of a subclass, it can be overridden, which is called the override of the method, also known as the overload 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:
' Optional class documentation string ' #类文档字符串
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:
Class Employee:
' Common 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, ", Salary:", 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.
"This would create first object of Employee class"
EMP1 = Employee ("Zara", 2000)
"This would 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
Class Employee:
' Common 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, ", Salary:", self.salary
"This would create first object of Employee class"
EMP1 = Employee ("Zara", 2000)
"This would create second object of Employee class"
EMP2 = Employee ("Manni", 5000)
Emp1.displayemployee ()
Emp2.displayemployee ()
Print "Total Employee%d"% Employee.empcount
Execute the above code to output the result as follows:
Name:zara, salary:2000
Name:manni, salary:5000
Total 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 the ' 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 the ' age ' property
SetAttr (EMP1, ' age ', 8) # Add attribute ' age ' value to 8
Delattr (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 (containing a tuple of all the parent classes)
The python built-in class property invocation instance is as follows:
#!/usr/bin/python
Class Employee:
' Common 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, ", Salary:", self.salary
Print "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__: Common base class for all employees
EMPLOYEE.__NAME__: Employee
EMPLOYEE.__MODULE__: __main__
Employee.__bases__: ()
employee.__dict__: {' __module__ ': ' __main__ ', ' displaycount ':
<function Displaycount at 0xb7c84994>, ' Empcount ': 2,
' Displayemployee ': <function displayemployee at 0xb7c8441c>
' __doc__ ': ' Common base class for all employees ',
' __init__ ': <function __init__ at 0xb7c846bc>}
Python Object Destruction (garbage collection)
Like the Java language, Python uses a simple technique of reference counting to track objects in memory.
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 = 40 # Create object <40>
b = A # Add reference, <40> count
c = [b] # Add Reference. Count of <40>
Del a # Reduce the count of references <40>
b = 100 # Reduce the count of references <40>
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 dies, and the __del__ method runs when the object is no longer being used:
#!/usr/bin/python
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, "destroyed"
PT1 = Point ()
Pt2 = pt1
PT3 = pt1
Print ID (PT1), id (PT2), id (PT3) # Prints the object's ID
Del pt1
Del pt2
Del Pt3
<pre>
<p> the results of the above example run as follows:</p>
<pre>
3083401324 3083401324 3083401324
Point destroyed
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
Class Parent: # define Parent class
parentattr = 100
def __init__ (self):
Print "Calling parent constructor"
def parentmethod (self):
print ' Calling parent method '
def setAttr (self, attr):
Parent.parentattr = attr
def getAttr (self):
print "Parent attribute:", parent.parentattr
Class Child (Parent): # define Child class
def __init__ (self):
Print "Calling child constructor"
def childmethod (self):
print ' calling child method '
c = Child () # instantiating a subclass
C.childmethod () # Methods for calling subclasses
C.parentmethod () # Call the parent class method
C.setattr (200) # Method of calling the parent class again
C.getattr () # Calling a method of the parent class again
The result of the above code execution is as follows:
Calling Child constructor
Calling child method
Calling parent method
Parent attribute:200
You can inherit multiple classes
Class A: # define your Class A
.....
Class B: # define your CALSS b
.....
Class C (A, B): # Subclass of 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.
Overloaded methods
If the functionality of your parent's method does not meet your needs, you can overload your parent class's methods in subclasses:
Instance:
#!/usr/bin/python
Class Parent: # defines the parental class
def myMethod (self):
print ' Calling parent method '
Class Child (Parent): # define Subclass
def myMethod (self):
print ' calling child method '
c = Child () # Subclass Instance
C.mymethod () # Subclass Call overloaded method
Execute the above code to output the result as follows:
Calling child method
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/python
Class 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 result of the above code execution is as follows:
Vector (7,8)
Hide Data
Data hiding in Python is very simple, do not need to add a keyword in front, as long as the class variable name or member function before adding two underscore the function of data hiding, so, for the class instance, its variable name and member function is not used, for its class inheritance class, is also hidden, so , its inheriting class can define its exact variable name or member function name without causing a naming conflict. Instance:
#!/usr/bin/python
Class Justcounter:
__secretcount = 0
def count (self):
Self.__secretcount + = 1
Print Self.__secretcount
Counter = Justcounter ()
Counter.count ()
Counter.count ()
Print Counter.__secretcount
Python includes the class name by changing its name:
1
2
Traceback (most recent):
File "test.py", line A, in <module>
Print Counter.__secretcount
Attributeerror:justcounter instance has no attribute ' __secretcount '
Python does not allow instantiated classes to access hidden 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:
1
2
2