Python tutorial (9): Class

Source: Internet
Author: User
Document directory
  • 9.2.1 example of scope and namespace
  • 9.3.1 class definition syntax
  • 9.3.2 Class Object
  • 9.3.3 Instance Object
  • 9.3.4 method object
  • 9.5.1 multi-Inheritance

Compared with other programming languages, the class mechanism of Python adds the smallest new syntax and semantics. It is a mixture of class mechanisms in C ++ and Modula-3. Python classes provide all the standard features of object-oriented programming. The class inheritance mechanism allows multiple base classes, and a subclass can override any method in the base class, A method can call methods of the same name in the base class. Objects can contain any number of data types. Just like a module, classes are involved in the dynamic nature of Python. They are created at runtime and can be further modified after being created.

In terms of C ++, the common class members (including data members) are public, and all member functions are virtual. In the Modula-3, the members that reference the object from the object's method are not abbreviated. The method function is declared to have an explicit first parameter to represent this object. It is provided implicitly during the call. Just like in Smalltalk, classes are themselves objects. This provides the introduction and rename semantics. Unlike C ++ and Modula-3, built-in types can be used as a base class for extension. Many built-in operators such as C ++ have special syntaxes and can be redefined for class instances.

9.1 Introduction to names and objects

The same object has its own personality and multiple names (in multiple ranges ). It is called an alias in other languages. Generally, you do not need to worry about Python for the first time. It can be safely ignored when processing immutable basic types. When variable objects are involved, aliases may have a surprising effect on the semantics of Python code. This is usually used for the benefit of a program, because the alias behavior is in some ways like a pointer. For example, passing an object saves costs because only one pointer is passed. If a function modifies the object passed as a parameter, the caller will see this change, removing the need for two different parameter transfer mechanisms, as in Pascal.

9.2 Python scope and namespace

Before introducing the class, I should not tell you some rules about the python scope. Class definition provides some neat tips for namespaces. You need to know how the scope and namespace work and fully understand what is happening. By the way, knowledge about this topic is useful to advanced Python programmers.

Let's start with some definitions.

A namespace is a ing from name to object. Many namespaces are currently implemented as Python dictionaries, but they are generally not obvious in any way and will change in the future. A namespace example is a set of built-in names, a global name in the module, and a local name in the function call. In a sense, a set of attributes of an object also forms a namespace. The important thing you need to know about namespaces is that there is absolutely no relationship between names in different namespaces. For example, two different modules can define a function maximize without confusion. The module users must use the module name as the prefix.

By the way, I call any name after a vertex as an attribute. For example, in the expression Z. Real, real is an attribute of Object Z. Strictly speaking, the name of the reference module is an attribute reference. In the expression modname. funcname, modname is a module object, and funcname is an attribute. In this case, there is a direct ing of the attributes of the module and the global names defined in the module. They share the same namespace.

The attribute can be read-only or writable. In the latter case, you can assign values to an attribute. Module attributes are writable. You can write modname. the_answer = 42. You can also use the del statement to delete writable attributes. For example, del modname. the_answer removes the attribute the_answer from the object named modname.

Namespaces are created at different times and have different lifecycles. The namespace containing the built-in name is created and not deleted when the python interpreter is started. The global namespace of a module is created when the module definition is read. Generally, the module namespace continues until the interpreter exits. The statements executed by calling at the top layer of the interpreter are either read from the script file or interactive. They are considered to be part of the _ main _ module, therefore, they have their own global namespaces. (The built-in name is actually in a module called builtins)

The local namespace of a function is created when the function is called and deleted when the function returns or raises an exception that is not processed in the function. (In fact, forgetting is a better way to describe what actually happens.) Of course, each call has its own local namespace.

A scope is a body area of the python program, where a namespace is directly accessed. Direct access means that an unlimited reference to the name will be searched in the namespace.

Although the scope is static, It is dynamically used. During execution, there are at least three nested scopes whose namespaces are directly accessed:

  • The innermost layer scope is first searched, including the local name.
  • Any closed function scope is searched from the nearest closed scope, including non-local but non-Global names.
  • The penultimate scope contains the global name of the current module.
  • The scope of the outermost layer. The final search contains the built-in name.

If a name is declared as global, all references and assignments are directed to the intermediate scope that contains the global name of the module. The Nonlocal statement can be used to re-bind variables found out of the innermost scope. If nonlocal is not declared, those variables are read-only (a Write Attempt to such a variable will create a new local variable in the innermost-layer scope, and the outer-range variable with the same name has not changed ).

Generally, the local scope references the local name of the current function. Outside the function, the local scope references the same namespace as the global scope: The namespace of the module. Class defines another namespace in the local scope.

It is important to realize that scope is the decision of this article. The global scope of the function defined in the module is the namespace of the module, no matter where it is called or through what alias. In other words, the actual name search is completed dynamically. At runtime, however, language definitions evolve toward static names, so do not rely on dynamic names during compilation (in fact, the local variable has been determined by the static state)

A special coincidence of python is that, without the influence of the global statement, the assignment of a name always enters the scope of the innermost layer. Assigning values does not copy data. They only bind names to objects. This is true for deletion: Statement del X deletes the binding of X from the namespace referenced by the local scope. In fact, all operations that introduce new names use local scopes: in particular, import statements and function definitions bind module or function names in local scopes.

The global statement is used to indicate that special variables reside in the global scope, where they should be thrown back. The Nonlocal statement indicates that special variables reside in a closed scope and should be bounced back.

9.2.1 example of scope and namespace

This example demonstrates how to reference different scopes and namespaces, and how global and nonlocal affect variable binding:

The output of the sample code is:

Note that the local assignment does not change the binding of scope_test of spam. The Nonlocal assignment changes the binding of scope_test in spam, and the global assignment changes the binding at the module level.

You can see that there is no previous binding to spam before the global assignment.

9.3 first read class

Class introduces a small new syntax, three new object types, and some new semantics.

9.3.1 class definition syntax

The simplest form of class definition is as follows:

Class definitions, like function definitions, must be executed before they have any effect. (You can put the class definition in the branch of an if statement or a function)

In practice, the statements in a class definition are usually function definitions. Other statements are also allowed and sometimes useful. The function definition in the class usually has a special parameter list form. The method is governed by the call convention.

When you enter a class definition, a new namespace is created and used as a local scope. Therefore, all assignments to local variables enter the new namespace. Specifically, the function definition binds the name of the new function here.

When a class definition is left normally, a class object is created. This is a basic packaging around the periphery of the namespace content created through class definition. In the next section, we will learn more about class objects. The original local scope (the one that is working before entering the class definition) is restored. The object of this class is bound to the name given in the class definition header.

9.3.2 Class Object

Class objects support two types of operations: Property Reference and instantiation.

In python, the standard syntax obj. Name is used for all attribute references. Valid attribute names are all the names in the namespace of the class when the class object is created. Therefore, if the class definition looks like this:

Therefore, myclass. I and myclass. F are valid property references and return an integer and a function object respectively. Class attributes can also be assigned values, so you can change the value of myclass. I by assigning values. _ Doc _ is also a valid attribute that returns the document string of the class.

Class instantiation uses function writing. Assume that the class object is a function without parameters and a new instance of the class is returned. For example:

Create a new instance of the class and assign this object to the local variable X.

The instantiation operation creates an empty object. Many classes like creating objects that allow instances to be customized to a specific initial state. Therefore, a class can define a special method called _ init _ (), like this:

When a class defines a _ init _ () method, class instantiation automatically calls the _ init _ () method for a newly created class instance. In this example, a new and initialized instance can be obtained as follows:

Of course, the __init _ () method can have parameters, which gives more flexibility. In that case, the parameter for the class instantiation operator is passed to the _ init _ () method. For example:

9.3.3 Instance Object

So what can we do for instance objects now? The only operation understood by an instance object is Property Reference. There are two valid attribute names, data attributes, and methods.

Data attributes correspond to instance variables in Smalltalk and data members in C ++. Data attributes do not need to be declared. Like local variables, they suddenly exist when they are assigned for the first time. For example, if X is an instance of myclass, the following code snippet prints a value of 16 without leaving a trace:

Another method is to reference instance properties. A method is a function of an object. (In Python, the term method is not unique for class instances, and there are methods for other object types .)

The valid method name of an instance object depends on its class. By defining, all the attributes of a class are the corresponding methods for defining its instances. In our example, X. F is a legal method reference, because myclass. F is a function, but X. I is not, because myclass. I is not. However, X. F is not the same as myclass. f. It is a method object, not a function object.

9.3.4 method object

Usually a method is called immediately after it is defined:

In the myclass example, this will return the string 'Hello world '. However, it is unnecessary to call a method immediately. X. F is a method object that can be stored elsewhere and called in the future. For example:

Will print Hello world until the end.

What happens when a method is called? You should note that X. F () is called without parameters, even if F ()'s Function Definition specifies a parameter. So what happened to the parameter? It is certain that python will cause an exception when a function requires a parameter but is not called, even if this parameter is not actually used.

In fact, you may have guessed the answer. The special thing about the method is that the object is passed in as the first parameter of the function. In our example, calling X. F () and myclass. f (x) are equal. Generally, calling a method with N parameters is equivalent to calling the corresponding function and inserting the object to which the method belongs to the first parameter in the parameter list.

If you still don't understand how the method works, it may make things clearer. When an instance attribute that is not a data attribute is referenced, its class is searched. If the name indicates that a valid class property is a function object, a method object is created by packing the instance object with the function object found together into an abstract object, this is the method object. When this method object is called using a parameter list, a new parameter list will be constructed from this instance object and this parameter list, this function object will be called using this new parameter list.

9.4 random remarks

Data attributes overwrite the method attributes with the same name. To avoid unexpected name conflicts, this will cause more difficult problems to be found in large programs, A clever way is to use some conventions to minimize the chance of conflict. Possible conventions include uppercase method names, a small and unique string prefix (or an underline) for data attribute names, a verb for methods, and nouns for data attributes.

Data attributes can be referenced by methods and common users of an object. In other words, classes are not available for pure abstract data types. In fact, there is nothing in Python that forces data hiding. It is based on conventions. (On the other hand, python is implemented in C, which completely hides Implementation Details and controls access to an object, if necessary; this can be used through Python extensions written in C .)

The client should carefully use the data attributes, and the client may disrupt the constant maintenance by stamping their data attributes. Note: The client can add their own data attributes to an instance object without affecting the validity of the method. Conflicts with names are avoided. A naming convention can save a lot of headaches here.

There is no simple way to reference data attributes (or other methods) in a method ). I found that this increases the readability of the method. when reading the method, there is no chance of conflict between local variables and instance variables.

Generally, the first parameter of a method is self. This is a convention. The name of self has no special meaning for python. NOTE: If your code does not follow the conventions, the readability will be reduced for other Python programmers. As you can imagine, a browser program also needs to rely on this convention to write.

Any function object is a class attribute that defines a method of the class instance. The function definition is closed in the class definition in this article. It is also possible to assign a function object to a local variable of the class. For example:

Currently, f, g, and H are attributes of class C and point to function objects. Therefore, they are all methods of the C instance. H and G are equal, this practice is usually confusing to the readers of the program.

You can call other methods by using the method property of the self parameter:

The method can reference a global name in the same way as a common function. The global scope associated with a method is the module that contains its definition. (A class is never used as a global scope.) It is rare for a person to use global data in a method. There are many valid global scopes. First, functions and modules imported into the global scope can be used by methods and functions and classes defined in it. Generally, classes containing methods are defined in this global scope. In the next section, we will find some good reasons why a method wants to reference its own class.

Every value is an object, so a class (also called its type) is stored as objct. _ class __.

9.5 inheritance

Of course, a language feature is not worth having a name class. If it does not support inheritance. The syntax defined by a subclass looks like this:

The name baseclassname must be defined in the scope that contains the subclass definition. Where the base class name is located, other arbitrary expressions are also allowed. This is useful. For example, when the base class is defined in other modules:

The execution of subclass definition is the same as that of the base class. When a class object is built, the base class is remembered. This is used to parse attribute references. If a required attribute is not found in the class, the search will be carried out in the base class. This rule applies recursively if the base class inherits other classes.

There is nothing special about subclass instantiation. derivedclassname () creates a new class instance. Method reference is parsed in the following way, and corresponding class attributes are searched. If necessary, the method reference is legal along the chain of the base class. If this returns a function object.

Subclass can override the method of the base class. Because a method has no privilege. when other methods of the same object are called, a method of a base class calls another method of the same base class and ends calling a method of a subclass that overrides it. (For C ++ programmers, all the methods in Python are actually Virtual)

The override method in a subclass is actually to expand rather than simply replace the Same Name method in the base class. There is a simple way to directly call the methods in the base class and call baseclassname. methodname (self, arguments ). This is occasionally useful to customers. (Note: In this global scope, if the base class is accessible as baseclassname, the above method can work)

Python has two built-in functions used together with inheritance:

  • Isinstance () is used to detect the type of an instance. isinstance (OBJ, INT) returns true if and only if obj. _ class _ Is Int or a class is inherited from Int.
  • Issubclass () is used to detect class inheritance. issubclass (bool, INT) is true because bool is a subclass of Int. However, issubclass (float, INT) is false because float is not a subclass of Int.
9.5.1 multi-Inheritance

Python also supports multiple inheritance forms. A class definition with multiple base classes looks like this:

For a variety of purposes, in the simplest case, you can think that the search for an attribute inherited from the parent class is depth first, from left to right, it will not be searched twice in a class when it is at the overlap of the inheritance layer. Therefore, if a property is not found in derivedclassname, then base1 is searched, and all base classes of base1 are recursively searched. If no base classes are found, base2 is searched, and so on.

In fact, it is a little more complex than above. The resolution order of the methods is dynamically changed to support collaborative calls of super (). This method also appears in some other multi-inheritance languages, which is more powerful than the super call in a single inheritance.

Dynamic sorting is necessary, in all cases of multi-inheritance, one or more diamond relationships are displayed. (at least one parent class can be accessed through multiple paths in the underlying class .) For example, all classes inherit from objects, so in any case, more than one path is provided to reach the object. To ensure that the base class is accessed no more than once, the dynamic algorithm returns a linear search order in one way and maintains the order specified in each class from left to right, that is to say, every parent class is called only once, which is monotonous (meaning that a class can be divided into categories without affecting the priority order of its parent class ). In combination, these attributes make it possible to design reliable and scalable classes using multiple inheritance.

9.6 private variables

Except for an object, the private instance variables that cannot be accessed do not exist in Python. However, there is a convention that is followed by most Python code. A name prefixed with the following line should be considered as a non-public part of the API (whether it is a function, A method or a data member ). It should be considered as a detailed implementation and subject to changes without notice.

Because there is a legal private-class member case (that is, to avoid name conflicts caused by subclass definitions), there is a limited support for this mechanism, called Name correction. Any identifier in the form of _ spam (at least two leading underlines, at most one trailing underline) is replaced by _ classname _ spam, the classname here is the name of the current class and removes the leading underline. This correction is completed and has nothing to do with the syntax position of the identifier as long as it occurs within the definition of a class.

Name correction is useful because it allows the subclass to override the method without breaking the internal method call of the class. For example:

Note: correction rules are designed mostly to avoid accidents. They can also be used to access or modify a variable that is considered private. This is even useful in special cases, just like debugging.

Note that the Code passed to Exec () or eval () does not consider the name of the class being called as the current class, which is similar to the role of the global statement, its function imposes the same limits on the compilation of byte code. The same restrictions apply to getattr (), setattr (), and delattr (), and when _ dict _ is directly referenced.

9.7 fragmented

Sometimes it is very useful to have a record like Pascal or a structure like C, which packs a few named data items together. An empty class can be well defined:

A piece of Python code requires a special abstract data type, which is often replaced by a class to simulate that data type method. For example, if you have a function to format data from a file object, you can define a class with the read () and Readline () methods to obtain data from a string buffer, and pass it as a parameter.

The instance method object also has attributes. M. _ self _ is an instance object with method M (), and M. _ FUNC _ is a function object corresponding to the method.

9.8 exception is also a class

User-defined exceptions are identified by classes. You can use this mechanism to create an extensible hierarchy of exceptions.

There are two new valid semantic forms for raise statements:

In the first form, the class must be an instance of type or its subclass. It is short for the following:

The class in a limit t clause can match an exception. If it is the same class as an exception or a base class of an exception (otherwise, a limit t clause lists a subclass, does not match a base class ). For example, the following code prints B, c, d in that order:

If the limit t clause is reversed, placing limit t B first will print BBB, and the first matching limit t clause will be triggered.

When an error message of an unprocessed exception is printed, the exception class name is printed, followed by a colon and a space, and finally the string representation of the instance, use the built-in STR () function for conversion.

9.9 iterator

Now you may have noticed that many container objects can use the for statement to iterate over it:

The access style is clear, concise, and convenient. The iterator is widely used and unified in Python. In this scenario, the for statement calls ITER () on the container object (). The function returns an iterator object, which defines the method _ next _ (). It accesses elements in a container each time. When there are no more elements, it raises a stopiteration exception and tells the for loop to terminate. You can use the built-in next () function to call the _ next _ () method. The following example shows how it works:

We have seen the structure behind the iterator protocol, which can easily add iterator behavior to your class. Define a _ ITER _ () method and return an object containing _ next. If the class defines _ next _ (), then _ ITER _ () can only return itself:

9.10 Generator

A generator is a simple and powerful tool to create an iterator. They are written as normal functions, but they use the yield statement whenever they want to return data. Every time next () is called on it, the generator starts again at the place where it leaves (it can record the data values that reside and the last statement executed ). An example shows how to create a generator easily:

Anything that can be done with a generator can be done with a Class Based on the iterator. To make the generator so compatible, the _ ITER _ () and _ next _ () methods are automatically created.

Another key feature is that local variables and execution statuses are automatically saved between each call. This makes the function easier to write and clearer than using instance variables such as self. Index and self. Data.

In addition to the automatic method creation and saving of the program status, when the generator ends, they automatically cause a stopiteration exception. In short, these features make it easy to create an iterator and do not work harder than writing a normal function.

9.11 generator expression

Some simple generators can be simply written as expressions, using a syntax similar to the list, but using parentheses instead of braces. These expressions are designed where the generator is immediately used by a closed function. Generator expressions are more compact than complete generator definitions, but have fewer functions and tend to be more friendly for memory usage than equal lists.

Example:

This article is the official website content translation, original address: http://docs.python.org/3/tutorial/classes.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.