When I started learning Python, I saw some tutorials and information, I feel that I have a relatively zero-oriented programming this aspect, I always feel that I have always feel that I have to never lead. It was only to understand something. This book is very reasonable for the chapter arrangement, and it is not just teaching you how to teach you why, I feel that it will benefit.
In the process of watching, I will write down some things, some translations for the book, have their own experience and test code.
In translation, some are directly translated, most of them are actually their own translation, but also add some of their own instructions. After all, my purpose is to understand the problem, I don't want to do so many hard translation let people fall fog. So I wanted to make an article, I have this article. The arrangement of the article is basically the same as the Charpter5 of Python in the Nutshell, but the content is much short.
Wilson Sun
-------------------------------------------------- -------------------------------------------------- ----------------
1.1 new object (New-style classes)
In the 2.2 and version 2.3 of Python, if the object directly or indirectly inherits the object of Python's built-in type, then it is a new object.
"Classic" is often the respect for the old things. Since it starts to launch a new object from version 2.2, there is certainly beneficial, so we should try to use new objects.
1.1.1 Built-in type: Object
Starting from Python 2.2, Object is a built-in type, which is also superclars for all other built-in types and new objects.
Inheriting the object of Object, you need to overload the method:
_ _new_ _ _
_Ninit____
_ _DELATTR_ _ _
_ _GetaTribute__
_ _Setattr_ _ _
__hash__
_ _repr_ _ _
_ _STR_ _ _ _ _
1.1.2 Class-Level Methods
The type of method is one of the features of the new object, there are two categories: static methods and object methods.
1.1.2.1 Static Methods
The static method does not exist of Bound and UNBound problems, which can be called directly. State a static method with StaticMethod, such as:
Class ACLASS (Object):
Def Astatic (): Print 'a static method'
Astatic = staticmethod (astatic)
Aninstance = aclass ()
Aclass.astatic ()
1.1.2.2 Class Method (Class Methods)
Class methods can be called on an example of the internal and classes of the class. Declare the ClassMethod, such as:
Class Abase (Object):
DEF ACLASSMET (CLS): Print 'a class method for', CLS.__name___
Aclassmet = ClassMethod (ACLASSMET)
Class ADERIV (ABASE): Pass
BINSTANCE = ABASE () DINSTANCE = aderiv ()
Abase.aclassmet () # prints: a class method for abase
Binstance.aclassmet () # Prints: a class method for abase
Aderiv.aclassmet () # Prints: a class method for aderiv
DINSTANCE.ACLASSMET () # Prints: a class method for aderiv
The first parameter of the class method is to call the object of this method.
1.1.3 new object
The new object also has the characteristics of all classic objects, but they have a more unique feature, _ _init_ _ and _ _new_ _
1.1.3.1 _ _init_ _
A new object C, which will directly or indirectly inherited the _ _init_ _ method, if you don't overload in C _ _init_ _ method, you pass to C _ _IT_ _ method any parameters will be ignored by Python.
In order to avoid chaos, it is recommended:
DEF __INIT __ (Self): Pass
In this way, if the parameters are passed correctly, Python will throw an exception.
1.1.3.2 _ _ new_ _
All new objects have a static method: _ _new_ _.
Suppose there is a new object C, now you want to create an instance x, then you will write: x = c (23)
The execution process is: Python first calls the _ _new_ _ method, _ _new_ _ will return an instance, if the instance is indeed, the instance is indeed, then _ _init_ _ will be called, if _ _new_ _ return instance is not C's instance, then this instance will not be initialized (_ _init_ _). This process is equivalent to the following code:
X = C._ _new_ _ (C, 23)
IF isinstance (x, c): C._ _init_ _ (x, 23)
You can also overload its _ _new_ _ method, this overload does not need StaticMethod to declare.
_ _new_ _ method can be used to return different instances, you can use this way to implement Factory plant mode, you can implement the Singleton Dynamic mode.
1.1.4 Instance of a new object
All features in the example of classic objects are equally equipped in an example of a new object, and the new object instance has some different features.
1.1.4.1 Properties
"Properties" here are relative to the method. When defining attributes inside the object, use Python's built-in type: Property. Examples are as follows:
Class Rectangle (Object):
Def _ _init_ _ (self, width, heigth):
Self.width = width
Self.heigth = Heigth
Def Getarea (Self):
Return Self.width * Self.Heigth
AREA = Property (Getarea, Doc = 'Area of The Rectangle') In the above example, Area is the properties of Rectangle, since the GET method is defined, it is read-only attribute. DOC is the DOCSTRING parameter of the property, and the effect of DOCSTRING is very similar to the comment, but it can be used at runtime compared to the comment, and it is a great advantage.
The syntax using Property is as follows:
Attrib = property (fget = none, fset = none, fdel = none, doc = NONE)
Attribute operation
Code example
Python's implementation
Read
n = x.attrib
Returns the FGET function value in the Property
Value
x.attrib = 54
Pass the value into the Fset function in Perperty
delete
Del
x.attrib
Call the FDEL function
In the classic object model, if you want to implement the above code, you should write this:
Class Rectangle:
Def _ _init_ _ (self, width, heigth):
Self.width = width
Self.heigth = Heigth
Def Getarea (Self):
Return Self.width * Self.Heigth
Def _ _Getattr_ _ (Self, Name):
if Name = = 'Area': return self.getarea ()
Raise AttributeError, Name
Def __Setattr__ (Self, Name, Value):
if Name = = 'Area':
Raise AttributeError, "Can't Bind Attribute"
SELF._ _DICT_ _ [Name] = Value
1.1.4.2 _ _slots_ _ _
_ _Slots_ _ _ _ _dict_ _, all methods and properties used to store instances. _ _dict_ _ is a dictionary (DICT) type, and _ _slots_ _ is a tuple type, so use _ _slots_ _ will save memory, which is also the unique purpose of using it. It should be noted that once the _ _slots_ _, then the original _ _dict_ _ will have no effect.
If an object will generate millions of instances at the same time, use _ _slots_ _ will play the purpose of saving memory, if only a few instances, then there is no need.
It should also be noted that _ _slots_ _ will not inherit by subclasses in the instance.
Example:
Class OptimizedRectangle (Rectangle):
_ _slots_ _ = 'width', 'Heigth'
1.1.4.3 _ _GetaTRibute_ _ _
The reference to the instance attribute is implemented in the Object_GetaTribute_ _ method. You can also overload this method to get some special effects. For example, you don't want the append method in the List to be called, you can do this:
Class ListnoAppend (List):
Def _ _GetaTribute__ (Self, Name):
if Name = = 'append': raise AttributeError, Name
Return List.__GetaTRibute__ (Self, Name) So, whenever X.Append is called, exceptions.
1.1.4.4 per-instance method
1.1.5 Inheritance in the new object
Inheriting this aspect, the biggest difference between the new object is to inherit the object of the internal type, and Python is allowed to inherit multiple inheritance.
1.1.5.1 Analytical order of the method
When there is inheritance, Python will go to the base class (base class) to find ways or attributes, especially when there is multiple inheritance relationships, what is the order of findings? This sequence of lookups is called resolution order.
Suppose there is class A. It directly inherits from B and C (order: B, c), B and C inherited from D.
The classic object model and the analysis of the new model object are shown below:
The parsing order of the classic object model is: the left is preferred, and the depth is preferred. So it's parsing order is: Pre-A-B-D-C-D.
The new object model is: A-B-C-D-Object
When writing a program, this parsing order of the classic object model may generate some problems, so change the parsing order in the new object will first parse the base class of the same level.
1.1.5.2 superclass call
When an override is a method, we tend to do some operations for the supermarket method, but in the case of multiple inherits, Python's current method parsing the order is not perfect.
Look at the following code:
Class A (Object):
DEF MET (Self):
Print 'a.met'
Class B (a):
DEF MET (Self):
Print 'b.met'
A.met (Self)
Class C (a):
DEF MET (Self):
Print 'c.met'
A.met (Self)
Class D (b, c):
DEF MET (Self):
Print 'D.met'
B.met (Self)
C.met (Self)
D = D ()
D.met ()
The code execution is as follows:
D.met
B.met
A.met
C.Met
A.met
It can be seen that the MET in A is called twice. If you can guarantee the same name in the superclass is only called once? This can be solved with SuperThon 2.2, Super is a new built-in type. Calling Super (Aclass, OBJ) will return OBJ's superclass.
The above code can do the following modification:
Class A (Object):
DEF MET (Self):
Print 'a.met'
Class B (a):
DEF MET (Self):
Print 'b.met'
Super (B, Self) .met ()
Class C (a):
DEF MET (Self):
Print 'c.met'
Super (C, Self) .met ()
Class D (b, c):
DEF MET (Self):
Print 'D.met'
Super (D, Self) .met ()
Note: TUPLE this word, seeing a variety of translations. In the SQL Server 2000 online manual of the MS, it translates it as "tuple", so he uses this translation.