- Object-oriented is a programmatic approach that is implemented based on the use of classes and objects
- A class is a template that wraps multiple "functions" in a template (which can be used to encapsulate variables common in multiple functions into an object)
- Object, an instance created from a template (that is, an object) used to invoke a function that is wrapped in a class
- Object-oriented three major features: encapsulation, inheritance, and polymorphism
This article details the members of the Python class, the member modifiers, and the special members of the class.
Members of the class
The members of a class can be divided into three main categories: fields, methods, and properties
Note: In all members, only the contents of the normal field are saved in the object, that is: how many objects are created based on this class, and how many normal fields are in memory. Other members are saved in the class, that is, only one copy is created in memory, regardless of the number of objects.
First, the field
Fields include: normal fields and static fields, they differ in definition and use, and the most essential difference is where the memory is stored in different places,
- Normal field belongs to object
- Static fields belong to class
definition and use of fields
As can be seen from the code above, "Ordinary fields need to access the" static field through the class access, in the use can be seen in the normal field and static field attribution is different. Its content is stored in a similar way as:
by but:
- Static field saves only one copy in memory
- Normal fields save one copy of each object
Scenario: When you create an object from a class, you use a static field if each object has the same field
Second, the method
Methods include: Common methods, static methods, and class methods, three methods in memory belong to the class, the difference is that the calling method is different.
- Normal method: Called by the object ; at least one self parameter; When the normal method is executed, the object that invokes the method is automatically assigned the value to auto;
- Class method: Called by the class ; at least one cls parameter; When the class method is executed, the class that invokes the method is automatically copied to the CLS;
- Static methods: Called by the class , no default parameters;
definition and use of methods
The same point: for all methods, it belongs to the class (non-object), so only one copy is saved in memory.
different points: The method callers are different, and the parameters that are passed in automatically when the method is called are different.
Third, attribute
If you already know the methods in the Python class, the properties are very simple, because the properties in Python are actually variants of the common method .
For attributes, the following three points of knowledge are available:
- Basic use of attributes
- Two ways to define a property
1, the basic use of attributes
definition and use of attributes
The definition and invocation of a property is a few points to note:
- When defining, add @property adorners on the basis of common methods;
- When defined, the property has only one self parameter
- When called, no parentheses are required
Method: Foo_obj.func ()
Property: Foo_obj.prop
Note: The attribute has the meaning that it can be used to create and access the exact same illusion of the field when accessing the property.
Property is a variant of the method, and if there are no attributes in Python, the method can completely replace its functionality.
Example: For the Host List page, each request is not possible to display all the contents of the database on the page, but by the function of paging to display locally, so when requesting data in the database to display the specified to obtain all the data from article M to Nth (that is: Limit m,n), this paging function includes:
- Calculates M and n based on the current page and total number of data bars requested by the user
- Request data from the database according to M and N
View Code
From the above, the function of the Python property is: A series of logical calculations inside the property, and finally the results are returned.
2. Two ways to define attributes
There are two ways to define a property:
- Adorners: Applying adorners on methods
- Static fields are: Static fields that define values as property objects in a class
Adorner mode: Apply @property adorner to ordinary method of class
We know that the classes in Python have classic and modern classes, and the properties of the new class are richer than those of the classic class. (If the class is following object, then the class is a modern Class)
Classic class with a @property adorner (as in the previous step)
View Code
New class with three kinds of @property adorners
View Code
Note: The properties in the classic class have only one access, which corresponds to the method that is @property decorated
The properties in the new class are accessed in three ways and correspond to three @property, @ method names. Setter, @ Method name. Method of Deleter Modification
Since there are three kinds of access methods in the new class, we can define three methods for the same attribute according to the access characteristics of several properties: Get, modify, delete
Example
Static fields, creating static fields with values as Property objects
Classic and modern classes are no different when creating properties using static fields
View Code
There are four parameters in the property's construction method
- The first parameter is the method name , which
对象.属性 automatically triggers the execution method when called
- The second parameter is the method name , which
对象.属性 = XXX automatically triggers the execution method when called
- The third parameter is the method name , which
del 对象.属性 automatically triggers the execution method when called
- The fourth parameter is a string that
对象.属性.__doc__ is called, and this parameter is the description of the property
View Code
Because there are three ways to create properties for static fields, we can define three methods for the same attribute based on the access characteristics of several of their properties: Get, modify, delete
Example
Note: The Python Web Framework Django view is in the request. POST is the property that is created using the static field method
Django Source
So there are two ways to define properties, namely adorners and static fields, and adorners are different for classic and modern classes.
Modifiers for class members
All members of the class have been described in more detail in the previous step, and there are two forms for each member of a class:
- Public members, accessible from anywhere
- Private members, only inside the class can the method
Private members and public members are defined differently : The first two characters are underlined when a private member is named. (except for special members, e.g. __init__, __call__, __dict__, etc.)
| 12345 |
class c: def __init__ ( self self .name = ' public field '      &NBSP, self = "private Field" |
Private members and public members have different access restrictions :
Static fields
- public static fields: classes are accessible, inside classes can be accessed, and in derived classes
- private static field: Only the class can be accessed internally;
public static fieldsprivate static fields
Normal field
- Public common fields: objects can be accessed, accessible within classes, and accessible in derived classes
- Private Normal field: Only within the class can be accessed;
PS: If you want to force access to a private field, you can access it through the object. _ Class name __ Private character Deming (for example: Obj._c__foo), and it is not recommended to force access to private members.
Public FieldsPrivate Fields
Methods, properties are accessed in the same way that a private member can only be used inside a class
PS: If you want to access a private property, you can pass the object. _ Class __ Property name
Special members of the class
The class members of Python and the member modifiers are described above to understand that there are three categories of fields, methods, and properties in a class, and that if there are two underscores before the member name, the member is a private member and the private member can only be called from within the class. No matter how people or things tend to be out of the way, Python's class members are the same, there are some special meaning members, the details are as follows:
1. __doc__
Represents the description of a class
View Code
2. __module__ and __class__
__MODULE__ represents the object of the current operation in that module
__CLASS__ represents the class of the object that is currently being manipulated
lib/aa.pyindex.py
3. __init__
Constructs a method that automatically triggers execution when an object is created from a class.
View Code
4. __del__
destructor, which automatically triggers execution when the object is freed in memory.
Note: This method is generally not defined because Python is a high-level language, and programmers do not need to be concerned with allocating and releasing memory because this work is done by the Python interpreter, so the destructor calls are automatically triggered by the interpreter when it is garbage collected.
View Code
5. __call__
The object is appended with parentheses to trigger execution.
Note: The execution of the construction method is triggered by the creation object, that is: Object = class name (), and the execution of the __call__ method is triggered by parentheses after the object, i.e.: Object () or Class () ()
View Code
6. __dict__
All members in a class or object
As we know above, the ordinary fields of the class belong to the object, and the static fields and methods in the class belong to the class, namely:
View Code
7. __str__
If the __str__ method is defined in a class, the return value of the method is output by default when the object is printed.
View Code
8, __getitem__, __setitem__, __delitem__
Used for index operations, such as dictionaries. Each of the above represents the acquisition, setting, and deletion of data
| 1234567891011121314151617181920 |
#!/usr/bin/env python# -*- coding:utf-8 -*- classFoo(object): def__getitem__(self, key): print‘__getitem__‘,key def__setitem__(self, key, value): print‘__setitem__‘,key,value def__delitem__(self, key): print ‘__delitem__‘,keyobj =Foo()result =obj[‘k1‘] # 自动触发执行 __getitem__obj[‘k2‘] = ‘wupeiqi‘# 自动触发执行 __setitem__delobj[‘k1‘] # 自动触发执行 __delitem__ |
9, __getslice__, __setslice__, __delslice__
The three methods are used for shard operations, such as: List
| 12345678910111213141516171819 |
#!/usr/bin/env python# -*- coding:utf-8 -*-classFoo(object): def__getslice__(self, i, j): print‘__getslice__‘,i,j def__setslice__(self, i, j, sequence): print‘__setslice__‘,i,j def__delslice__(self, i, j): print‘__delslice__‘,i,j obj =Foo()obj[-1:1] # 自动触发执行 __getslice__obj[0:1] = [11,22,33,44] # 自动触发执行 __setslice__delobj[0:2] # 自动触发执行 __delslice__ |
Ten. __iter__
For iterators, lists, dictionaries, and tuples can be used for loops because the type internally defines the __iter__
The first stepStep TwoStep three
As you can see from the above steps, the for loop iteration is actually ITER ([11,22,33,44]), so the execution process can be changed to:
| 1234567 |
#!/usr/bin/env python# -*- coding:utf-8 -*-obj = iter([11,22,33,44]) for i in obj: printi |
For loop syntax internal
__new__ and __metaclass__.
Read the following code:
| 123456 |
classFoo(object): def __init__(self): pass obj =Foo() # obj是通过Foo类实例化的对象 |
In the above code, obj is an object instantiated through the Foo class, in fact, not only obj is an object, but the Foo class itself is an object because everything in Python is an object .
If all things are object theory: The Obj object is created by executing the constructor of the Foo class, then the Foo class object should also be created by executing the constructor of a class.
| 12 |
printtype(obj) # 输出:<class ‘__main__.Foo‘> 表示,obj 对象由Foo类创建printtype(Foo) # 输出:<type ‘type‘> 表示,Foo类对象由 type 类创建 |
Therefore, theobj object is an instance of the Foo class, and theFoo class object is an instance of the type class , that is, the Foo class object is created through the constructor of the type class.
Then there are two ways to create a class:
a). Normal mode
| 1234 |
classFoo(object): def func(self): print‘hello wupeiqi‘ |
b). Special method (constructor for type class)
| 1234567 |
def func ( self Code class= "python spaces" > print ' Hello Wupeiqi ' foo = type ( ' Foo ' object Code class= "Python Plain"), { : func}) #type第一个参数: class name #type第二个参数: base class for the current class #type第三个参数: Member of Class |
= = Class is generated by instantiation of the type class
So the question is, class default is generated by the type class instantiation, how does the type class implement the Create class? How do classes Create objects?
A: There is a property in the class __metaclass__, which is used to indicate who created the class by whom it was instantiated, so we can set a derived class of type class for __metaclass__ to see the process of class creation.
View Code
Python Object Oriented-Next