Object-oriented Python (1)

xiaoxiao2021-03-06  43

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

-------------------------------------------------- -------------------------------------------------- ----------------

Python is an object-oriented programming language. However, it is not like other object-oriented languages, Python does not force you to write programs with object-oriented ways, which also allows you to write modules, functions, etc. in a process-oriented approach.

1.1 Classic Object (Classic Class)

At 2.1 and previous version of Python, you can only program with this object model of classic objects. Python in 2.2 and 2.3, classic objects are also the default object model.

1.1.1 Some of the characteristics of classic objects:

l You can call an object like the function is the same as the function. Once called, an instance of the object is established.

l You can name the property inside the object.

l Attributes can be a data type or a function type.

l If attribute is a function type, then it will see a method of objects (Method).

l Python specifies a special naming mode for the function, enclosing the function name with the two underlines, for example: __ methodname__.

l The object can inherit.

1.1.2 object statement

Declare the syntax of the object:

Class ClassName [(Base-Classes)]:

Statement (s)

ClassName is a function name.

The value of base-classes must be an object, separated by a comma, which is equivalent to superclass in Java.

The inheritance relationship can be transmitted. If C1 is a subclass of C2, C2 is a subclass of C3, then C1 is also a subclass of C3.

Built-in functions ISSUBCLASS (C1, C2) can determine inheritance relationships, if C1 is a subclass of C2, then the function returns TRUE. Since any classes are seen as their own subclasses, if there is class C, IssubClass (C, c) returns TRUE.

DEF declaration syntax and class declaration grammar difference:

When the DEF declares, the first few parentheses in front of the colon, even if it does not have any parameters; but the Class declares, only when the class class is based, it needs to be written in parentheses. 1.1.3 object body

1.1.3.1 Attributes inside the object

Call its properties inside the object, write directly to its property name, such as:

Class C3:

X = 23

Y = x 22 # MUST USE JUST X, NOT C3.X

However, if the method is defined within the object, you need to write a full name of the location in the object to call the object, such as:

Class C4:

X = 23

Def amethod (Self):

Print C4.x # Must Use C4.X, Not Just X

When the object is declared, some attributes have been implicitly declared.

__name__: Name of the class

__base __: Tuple object, all base classes of the object

__dict __: DICT object, place all properties of the object

For example: the object C is attribute S, then C.S = X is equivalent to C._ _dict_ _ ['s'] = X

1.1.3.2 Functions inside the object

The internal function of the object is similar to the ordinary function writing, but the first parameter of the function is written as self, such as:

Class C5:

Def Hello (Self):

Print "Hello"

1.1.3.3 Private variables

Declaration of private variables, just add two underscores in front of the variable name, such as private variables in the interior of class C, should be declared as: __ user.

In fact, when Python is compiled, __user will be changed to _c__user (ie _classname__variablename).

Regardless of whether or not, in the object, the variable starting with a downline is considered private variables.

1.1.4 instance

Looking back at the first point in the previous "classic object": "You can call an object like the function is the same as the function." When you create an instance, you created this: aninstance = C5 ()

1.1.4.1 _ _init_ _ _

If there is an object of an object, there is or inheritable _ _init_ _ method, then when this object is called (using the words on Java can be called instantiated), _ _init_ _ method will be automatically called.

_Ninit_ _ method can not have a return value, and can only return NONE if you need to jump or return.

E.g:

Class C4:

DEF __INIT __ (Self):

Return 'sss'

A = C4 ();

Python will report an error: Traceback (MOST Recent Call Last):

File ", line 1, in -toplevel

A = C4 ();

Typeerror: __init __ () Should Return None

The main purpose of _Ninit_ _ method is to assign values ​​to objects attribute to the object when creating an object instance. Do you can increase the readability of the program. If there is no _ _init_ _, then you can't bring any parameters when you call the object.

1.1.4.2 Properties in the instance

Use points (.) To access properties in the instance. Even if an object has been instantiated, you can still add any properties to an instance and assign it.

Class C7: Pass

Z = C7 ()

Z.x = 23

After the instance is created, the instance will be automatically coupled with two properties: _ _class_ _: object to which instance belongs

All attributes of _ _DICT__: Examples (instance themselves and properties of their objects) such as: Class C6:

DEF _ _INIT_ _ (Self, N):

Self.x = n

A = C6 (234)

a.y = 213213

a .__ dict__

# 执行 结果: {'Y': 213213, 'x': 234}

1.1.4.3 Factory function

I want to use the most factory mode in the design mode, which is used to create an instance of an object. In Python, the most direct way to realize the plant mode, it seems to return different instances with _ _init_ _ to return different instances, but unfortunately, _ _init_ _ maximum can only return NONE. Therefore, to implement factory model, the best way is to write a function to return different instances, such functions, can be called Factory function.

As example, ApproPriateCase is a factory function.

Class Specialcase:

Def Amethod (Self): Print "Special"

Class Normalcase:

Def Amethod (Self): Print "Normal"

Def appropriatecase (isnormal = 1):

IF isnormal: return normalcase ()

Else: Return Specialcase ()

Aninstance = appropriatecase (isnormal = 0)

Aninstance.Amethod ()

1.1.5 attribute reference

Suppose X is an instance of object C, how is it to find its value when referenced to X.Name? Summary with the easiest words, that is, by small to a long to far, look for the value of Name in turn.

Something is specifically, looking at the following manner:

l If x.Name is X._ _dict_ _, the key, then return to x._ _dic_ _ ['name'] (looking for itself)

1 Otherwise, look for Key in C.__dict_ _, then return to C.__dict_ _ ['name'] (Find object)

1 Otherwise, find the base class of C, continue to press the above two steps in C._ _bases_ _ _ Find the base class of the object to be

l Otherwise, throw anomalies: AttributeError

1.1.6 Binding and non-bound (Bound and UNBound)

The reference to the property is told above, the binding of the method and the non-bound actually involved method are the problem. The method actually uses a function to be implemented. When the method is referenced, it is not directly returned to its corresponding function, but the function is loaded into the Bound or UNBOound method.

The difference between Bound and UNBound is that Bound will associate a particular function, and the UNBOUND is the opposite. If there is no name attribute, the direct use of the function name (after the function name is not brackets), it can be observed.

Assume Objects C and instance x:

Class C:

A = 1

DEF G (Self): Print "Method G in Class C"

X = c ()

Print X.g

# 执行 结果: >

Print C.g

# 执行 结果:

The above execution results show that X.G is bound to the C.G () function, so X.G () will have a result returns; and C.G is not bound, so the C.G () has no result.

1.1.6.1 Non-binding

If it is in a non-binding state, when a function is referenced, the actually returned is the unbound method, which contains the function inside. There are three read-only properties in the UNBound method.

IM_CLASS: The object being referenced by the function

IM_FUNC: Quote

Im_self: Always for NONE

The non-binding method can also be called, and the instance name of the IM_CLASS object is required as the first parameter, then the IM_FUNC function is returned.

For example, the above C.G () has no result, but C.G (X), X is an instance of C, and the correct execution of the C.G () function can be obtained.

1.1.6.2 Binding

When X.g () is performed, the bound method is returned. The Bound method is similar to the UNBOUND method, there are three read-only properties: IM_CLASS, IM_FUNC, IM_SELF, but the difference is that the value of im_self is x.

1.1.7 inheritance and overload

It is not difficult to see the implementation of Python inheritance from the previous "attribute reference" lookup method. If X is an instance of C, when the XG () is called, Python first looks in X._DICT_ _ 没有有 没有, didn't look for C._ _dict_ _, if you don't look for C._ _Base_ _? . The base class of C.__base___, the inheritance of the object is realized. With this mechanism, overload is also achieved.

1.1.7.1 super agriculture

In subclasses, it is possible to use a superclass properties, then use the super-class proxy mechanism, which is actually called the superclass function with the unbound mode. E.g:

Class Base:

DEF GREET (Self, Name): Print "Welcome", Name

Class Sub (Base):

DEF GREET (Self, Name):

Print "Well Met and",

Base.greet (Self, Name)

X = SUB ()

x.greet ('alex')

Super-class agent is often used

_ _init_ _ method, because

Python

Sub-class

_Ninit_ _ method does not automatically call the _ _init_ _ method in its superclass, so it is necessary to use this supermarket proxy mechanism to manually call.

转载请注明原文地址:https://www.9cbs.com/read-73500.html

New Post(0)