Python programming (8)

zhaozj2021-02-08  257

Chapter 9

Python is a language that is really facing objects, which only adds a few new grammar to implement classes. Its class mechanism is a mixture of C and MODULA-3 class mechanisms. Python's class does not strictly restrict the user's modification of the definition, depending on the user's consciousness and definition. However, Python maintains a complete power for the most important features of the class. The class inheritance mechanism allows inheritance of multiple base classes, and exports any method of the base class to overload the base class, the method can call the synonymous method of the base class. Objects can contain any private data.

Terminology with C , all class members (including data members) are public, and all member functions are virtual (Virtual). There is no special build function or destruction function (DESTRUCTOR). As in MODULA-3, there is no way to reference object members from the object's approach: the method function must be used as the first parameter as the first parameter, and it is automatically provided when calling. Like in SmallTalk, the class itself is also an object. In fact, the meaning of the object here is wider: all the data types in Python are objects. As in C or Modula-3, the built-in type cannot be extended by the user as a base class. Also, like C but is not like modula-3, most of the built-in functions of special syntax (such as an arithmetic operator, subscript, etc.) can be redefined as class members.

9.1 About Terminology

Python's object concept is relatively wide. The object is not necessarily an example of a class, because it is different from SmallTalk, and the data type of Python is not all classes, such as the basic built-in type integer, the list, etc., or even more Quirky types, such as files are not classes. However, all of the data types of Python are more or less with some similar objects.

The object is a separate identity, and the same object can have multiple names, which is called alias in other languages. The benefits of doing this are not obvious at first glance, and there is no difference in non-variable types (numbers, strings, programs (tuple)). However, the alias sentence has an impact on the program containing variable objects such as a list, a dictionary, and a program related to the program such as a file, a window, which can be conducive to programming, because the alias has some similar pointers: For example, pass an object easier, because Just pass a pointer; if a function modifies the object as a parameter transfer, the modification result can be transferred. This will use two parameter transfer mechanisms without PASCAL.

9.2 Python Scope and Name Space

Before introduced into the class, we must talk about Python's role in the domain rules. Class definitions use the namespace, you need to understand how Python handles the roles and namespaces to fully understand the use of classes. In addition, the domain rule is also a knowledge that a senior Python programmer must master.

Some definitions are given first.

The namespace is a mapping from the name to the object. Most of the namespace is currently implemented with a Python dictionary, but this is generally not noticed and may change in the future. Below is some examples of name space: the names of the built-in in Python (such as ABS () and other functions, and built-in exception names); the global name in the module; the local variable name in the function call. All attributes in a sense in a sense also constitute a namespace. About the most important thing about the namespace must know the name of the different namespaces without any contact; for example, two different modules may define a function called "maximize" without causing confusion, because the module must be before the function name Plus the module name as a modification.

In addition, in Python, any one of the names after the period can be referred to as an attribute, for example, in the expression z.REAL, REAL is an object z attribute. Strictly speaking, reference to the name in the module is attribute reference: In the expression modname.funcname, MODNAME is a module object, and FuncName is an attribute. In this case, there is a direct mapping between the module properties and the module definition: they use the same namespace! The attribute can be read-only or writable. When you can write, you can assign a value for attributes. The module properties are writable: you can write "MODNAME.THE_ANSWER = 42". The writable properties can also be flaws with the DEL statement, such as "del modname.the_answer".

Namespaces are created with different time, with different survival cycles. The namespace containing the Python built-in name When it is created when the Python interpreter is started, and it will not be deleted. The global namespace of the module is created when the module definition is read, in general, the module namespace has always been exit to the interpreter. The statement executed by the top layer of the interpreter is executed, whether it is from a script file or interactive input, it belongs to a module called __main__, so it exists in its own global name space. (The built-in name is actually exist in one module, this module is called __builtin__).

The local namespace of the function is created when the function is called, and when the function returns or generates an exception that cannot be handled within the function, it is deleted. (In fact, it is said that this name space is more in line with the actual situation.) Of course, recursive calls have their own local namespaces in each recursive.

A scope is a text area in the Python program, where a namespace can be accessed directly. "Direct Access" refers to the objects in the namespace directly using the names that do not add modified names.

Although the action domain is static, the scope is dynamic during use. At any time, there is always three scopes in use (ie, there are three namespaces are directly accessible): the innermost scope, first search, contain partial names; middle-level scope, Secondly, it is searched, including the global name of the current module; the outermost scope finally searched, including the built-in name.

Under normal circumstances, local scope references the local name of the current function, where partial is from the source of the text. In the exterior of the function, the local scope is used with the global scope: the namespace of the module. Class definitions add another namespace in the local scope.

Be sure to pay attention to the scope is determined according to the text location in the source program: the global scope of the function defined in the module is the namespace of the module, no matter where the function is called or what is called. On the other hand, the search for the name is dynamically performed in the program run. However, the definition of the Python language is also evolving, and it may develop to static name resolution in the future, so do not depend on dynamic name analysis! (In fact, the local name is already static).

One of Python is that assignments always enter the innermost role domain. About deletion is also the case: "DEL X" removes X's name binding from the namespace corresponding to the local scope (Note You can correspond to one object in Python, so deleting a name is just deleting this name and its object) Contact and not necessarily delete this object. In fact, all operations that introduce new names use local scope: special, import statements, and function definitions to bind the module name or function name into the local scope. (You can use the Global statement to specify Some variables belong to the global name space). 9.3 initiative

The class introduces some new grammar, three new object types, and some new semantics.

9.3.1 Class definition syntax

The simplest form of the definition is as follows:

Class class name:

.

.

.

Like a function definition (DEF statement), class definition must be executed before it can take effect. (Can even define the class definition in a branch or function of the IF statement). When actually use, the statement in the class definition is usually the function definition, and other statements are also allowed, sometimes useful - we will mention this later. The function definition in the class typically has a special form of self-emission table, which is dedicated to the method of calling conventions - this will also discuss in detail later.

After entering the class definition, a new namespace is generated, which is used as a local scope - therefore all the assignments of local variables enter this new name space. In particular, the function definitions binds the function name and the new function in this name space.

When the function defines the normal end (from the end of the end), a class object is generated. This is basically an object that will be wrapped in the namespace of the name of the class definition; we will learn more knowledge of class objects in the next section. The original local scope (that role before entering the class definition) is recovered, the class object is bound to the name specified by the class object definition header.

9.3.2 objects

Class objects support two operations: attribute references and instantiation. The properties reference format is the same in the format of other attributes in Python, ie obj.name. A valid attribute name includes all the names in the class name space when generating class objects. So, if you define the following:

Class myclass:

"A Simple Example Class"

i = 12345

DEF f (x):

Return 'Hello World'

Then myclass.i and myclass.f are valid attribute references, which return an integer and a function object, respectively. You can also assign a class attribute, so you can assign a value for MyClass.i to change the value of this property.

__doc__ is also a valid property, which is read-only, returned to class document strings: "a Simple Example Class".

Class instantiation usage function mark. As long as this class object is seen as a function without an argument, it returns a class instance. For example (assuming the class above):

x = myclass ()

A new instance of such a class can be generated and assigned an instance object to a local variable x.

9.3.3 instance object

How do we use instance objects? Class instances only know this kind of operation. There are two types of effective attributes.

The first class attribute is called data properties. Data properties are equivalent to "instance variable" in SmallTalk, and "Data Members" in C . Data members do not need to declare, and do not need to exist in class definitions, like local variables, as long as one assignments it will be generated. For example, if x is an instance of the above myclass class, the following example will display the value 16 without any traces:

x.counter = 1

While x.counter <10: x.counter = x.counter * 2

Print X.counter

Del x.counter

The second type of attribute reference that can be understood by a class instance is a method. The method is "a function of" a "an object. (In Python, the method is not only used for class instance: Other object types can have a method, for example, the list object also has an Append, Insert, Remove, Sort and other methods. However, unless otherwise explained We use the method Refers to the method of class instance objects).

The effective method name of the class object depends on its class. According to the definition, all types of classes are the corresponding methods of the function object attributes. So in our example y, X.f is an effective method reference, because myclass is a function; X.I is not a method reference, because myclass.i is not. But x.f and myclass.f are not the same thing --X.f is a method object rather than a function object.

9.3.4 Method Object

The method is generally called directly, for example:

X.f ()

In our example, this will return the string 'Hello World'. However, it is also possible to call the method without directly: X.f is a method object, which can save it again. E.g:

XF = x.f

While 1:

Print XF ()

"Hello World" will not be displayed.

What happened when calling a method? You may have noticed that the X.f () call does not have an argument, and the function f has an argument when calling. What is the variable? Python If you call a function that requires an argument, it will definitely generate an exception error - even if the own variable does not need to use ...

In fact, you can guess the answer: The difference between the method and the function is that the object is automatically transmitted to the method as the first independent index of the method. In our example, call X.f () equivalent to call myclass.f (x). Generally, the modified modification method is equivalent to the insertion of the object to be inserted into the first argument before the corresponding function will be called.

If you don't understand how the method works, you can help it. When references the instance properties of non-data properties, it will be searched. If the attribute name is a valid function object, generate a method object, package the instance object (pointer) and function objects together: this is the method object. When the method object is called with a self-variable table, it is opened, and the instance object and the original variable table are combined to form a new self-variable table, and the function is called with this new argument table.

9.4 Some explanations

At the same time, the data attribute will override the method properties; in order to avoid accidental name conflicts, this will cause difficult to find errors in large programs, it is best to distinguish between a naming convention, for example, all method names At the beginning of the uppercase, all data attributes begin with a unique string (or just a downline), or the method name is used by the name of the verb.

Data attributes can be referenced by the normal user ("Customer"). In other words, the class cannot be used to construct an abstract data type. In fact, there is no way in Python to force data hidden - these are based on conventions. (On the other hand, the implementation of Python is written with C, which can fully hide the implementation details, if necessary, can control object access; written by Certhon expansion modules also have the same characteristics).

Customers must carefully use the data properties - customers may destroy the consistency of class data maintained by class methods because of the data properties of the class object. Note that customers only take to avoid the name conflict to increase new data properties for instance objects without affecting the effectiveness of the method - here, effective naming conventions can save a lot of trouble. There is no shorthand approach to data attributes (or other methods) to access this object within the method. I think this in fact adds the program's readability: Whether local variables and instance variables are not confused in the method definition.

It is used to the first self-variable of the method called Self. This is just a habitual usage: Name Self does not have any special meaning in Python. However, because users use this practice, violating this practice may make other Python programmers don't easily read your programs, you can imagine that some types of browsing programs depend on this practice).

Any function object as class properties define a method for the instance of this class. The definition of the function is not necessarily inside the class definition: as long as a function object is assigned to a local variable within the class. E.g:

# Function Defined Outside The Class

DEF F1 (Self, X, Y):

Return MIN (X, X Y)

Class C:

f = f1

DEF G (Self):

Return 'Hello World'

h = g

Now f, g, and h are attributes of class C and point to function objects, so they are all methods of c 's instance - where H is completely equivalent to G. Note that we should avoid this usage to avoid mislead readers.

Methods can be referenced to this class with the SELF argument representative of the object, such as:

Class Bag:

DEF EMPTY (Self):

Self.Data = []

DEF Add (Self, x):

Self.Data.Append (x)

Def AddTwice (Self, X):

Self.Add (x)

Self.Add (x)

Instantiation operation ("call" a class object) Generate an empty object. Many class requirements generate classes with known initiative. To do this, the class can define a special method called __init __ (), such as:

DEF __INIT __ (Self):

SELF.EMPTY ()

A class defines the __init __ () method, and the class is automatically called to call the __init __ () method for the newly generated class instance. So in the BAG example, you can use the following procedure to generate an instance of new initialization:

X = Bag ()

Of course, __ init __ () method can have an argument so that greater flexibility can be achieved. In this case, the argument specified when the class is instantiated is passed to the __init __ () method. E.g:

>>> Class Complex:

... def __init __ (self, realpart, iMagpart):

... Self.R = RealPart

... self.i = iMagpart

...

>>> X = Complex (3.0, -4.5)

>>> X.R, X.I

(3.0, -4.5)

The method can reference the global name as the normal function. The global scope of the method is a module that contains class definitions. (Note that the class is not used as a global scope!) Although we rarely need to use global data in the method, there are many legitimate uses: For example, the functions and modules imported into the global scope can be used. The functions and methods defined in the same module can also be used. The class containing this method is generally defined in this global scope. We will see why a method we need to quote your class!

9.5 inheritance

Of course, if you don't support inheritance, you can't talk about "classes". The definition method of the derive class is as follows: Class export class name (base class name):

.

.

.

The "base class name" must be defined in the scope of the export class definition. In addition to giving the base class, an expression can also be given, which is useful when the base class is defined in other modules, such as:

Class export class name (module name. base class name):

The way to export the class defined run and the base class run is the same. The generated class is, the base class is memorized. This is used to resolve attributes: If the required properties in the class are not found, they go to the base class to find. If the base class also has a base class, this rule is recursively applied to a higher class.

Export classes do not have any special rules when instantiation. "Export Class Name ()" Generates a new instance of this class. Method Reference Solution: Search the corresponding class properties, if necessary, to the base class level class class, if you find a function object is a valid method reference.

Export classes can rewrite the method of the base class. Because the method does not have special permissions when calling other methods of the same object, if a method in the base class calls another method of the same base class, the method called in the derived class may be rewritten after being derived. The method is. (For C programmers: all methods in Python are "virtual functions").

The method of rewriting in the export class may be that the same name method of the expansion base can not be expanded instead of the original method. The export class calling the base class is very simple: "base class name. Method name (Self, self-variable table)". This approach is occasionally useful for class users. (Note that only the base class can be used when the base class is defined or imported in the same global role.

8.5.1 multiple inheritance

Python also supports limited multiple inheritance. The class definition format with multiple base classes is as follows:

Class export class name (base class 1, base class 2, base class 3):

.

.

.

Regarding multiple inherits, just explain how to solve class attribute references. Class properties references are depth priority, from left to right. Therefore, if an attribute is not found in the export class definition, then look for in the base class 1, and then (recursively) in the base class of the base class 1, if you are not found, you find it in the base class 2. , So on.

(Width to some people - first lookup in the base class 2 and base class 3 to find the base class of the base class 1 - it looks more natural. However, this requires you to determine the base class 1 Attribute conflicts of base classes 2 clearly know that this property is defined in the base class 1 itself or in its base class. Depth priority rules are not distinguished by one attribute of the base class 1 or inheritance).

Obviously, if you use multiple inheritance if you do not add to a multi-inheritance, you will cause the demise of the program to maintain, because Python avoids the name conflict only rely on habits. A well-known question of multiple inheritance is that two base classes exported from the same base class when derived. Although it is easy to think of this situation (example only "instance variable" or data attribute is used in common base class), this approach is unclear.

9.6 private variable

Python has some support for private members. Any icon __spam is described in the form of an identifier (at least two leading scribes, at most ended underscores) is currently replaced with _classname__spam, where ClassName is the result of the class name removed. This arranging regardless of the syntax position of the identifier, can be used to define an existing instance, variables, methods, and global variables, and even save other types of other classes for this class. If the disturbed name exceeds 255 characters, truncation may occur. Do not discontinue only when the class or class name is underlined.

The purpose of the name is to give a simple method for defining "private" instance variables and methods, do not need to worry that other classes of it will define the same name variable, not afraid of the variables of the code. Note that the crowd rules are mainly to avoid accidental errors, and if you want to do it, you can still access or modify private variables. This is even useful, such as the debugger to use private variables, which is why this vulnerability is not blocked. (Small error: Export classes and base classes to use the same name to use the private variables of the base class). Note that the code passed to Exec, EVAL () or evAlFile () does not think that the class name of the class that calls them is the current class, which is similar to the Global statement, and the global role is limited to the code compiled by one byte. The same limitations are also applicable to getAttr (), setattr () and delattr (), as well as direct access __dict__.

The class in the following example implements its own __getattr__ and __setttr__ method, saving all properties in a private variable, which is feasible in Python's new version:

Class VirtualAttributes:

__vdict = none

__vdict_name = locals (). Keys () [0]

DEF __INIT __ (Self):

Self .__ dict __ [self .__ vdict_name] = {}

DEF __GETATTR __ (Self, Name):

Return self .__ vdict [name]

DEF __SETATTR __ (Self, Name, Value):

Self .__ vdict [name] = value

9.7 supplement

Sometimes we want to have a type similar to "RECORD" or C "Struct" like Pascal, you can combine several named data items. An empty class can meet this needs well, such as:

Class Employee:

PASS

John = Employee () # Generates an empty staff record

# 记

John.name = 'john doe'

John.dept = 'computer lab'

John.salary = 1000

A Python program that needs to be entered as input is often accepted as input as an input, which simply impars a method of data types that should be entered. For example, if you have a function that is used to format data in a file object, you can define a class with method read () and readline (), which may not be input from file input but from a string buffer Zone input, use this class as an argument.

Example method objects also have attributes: m.im_self is the instance belonging to the method, M.IM_FUNC is a function object corresponding to the method.

9.7.1 Exceptions can be class

User-defined exceptions can be clasped outside of the string object. This can define an extended layered class exception structure.

There are two new effective formats in the RAISE statement:

RAISE class, instance

Raise instance

In the first form, "instance" must be an example of an example of "class" instance or "class" export class. The second form is

Raise instance .__ class__, instance

Shorthand. Except statement can be listed in addition to the list of string objects. The classes listed in the Execpt clause If the exception class or base class is matched (in turn, if the exception is not for the exception to the export class, if it is exported in -except, it is not matched). For example, the following program displays B, C, D:

Class B:

PASS

Class C (b):

PASS

Class D (c):

PASS

For C in [B, C, D]:

TRY:

Raise C () Except D:

Print "D"

Except C:

Print "C"

Except B:

Print "B"

Note If the order of the Except clause is turned down ("Except B" is in the forefront), the program will display B, B, B - because the first matching Except clause is triggered.

When the exception is not processed is class, the class name is displayed in the error message, followed by a colon and a space, and finally the instance is converted to the result of the string with the built-in function STR ().

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

New Post(0)