[Python3 Tutorial] The Nineth Chapter. Classes (Class)

Source: Internet
Author: User
Tags class definition memory usage

Finally to the class, I feel the recent translation speed is very slow ah. 9.1 A Word about Names and Objects

The same object can be bound to different names, and other languages call this feature an alias (as the name suggests ...). )。 This feature may not be very well understood at first, but it will not affect the use of immutable objects. But this feature can be surprisingly effective when using modifiable objects, because aliases are limited to pointers, so the overhead is low when data is passed, and functions can modify objects when they are passed in as arguments. 9.2 Python Scopes and namespaces

Before introducing the class, let's introduce the scope rules. The definition of a class has some tips on namespaces, you need to know his rules to understand well, and by the way, this part of the knowledge is very important to the young people who are motivated. So here we go.

A namespace is a mapping relationship between a name and an object, and most namespaces are implemented in a dictionary, but we don't see them, and they are mutable. Examples include built-in functions and variable names, global variables for a module, local variables for a function declaration, and so on. One focus is that variable names in different namespaces have no relationship. For example, two modules have a method called MaxSize, the user must use the module name in the front as a cosmetic to prevent confusion occurs.

By the way, we call the things behind the dots attributes such as z.real. Where Real is an attribute of Object Z, strictly speaking, the method within the module is also an attribute of the module: for example, module.funcname.modname in this expression, FuncName is a property of the modules. This ensures that the properties of the module have a clear relationship with his global variables, and they use a common namespace.

The read and write permission of the attribute can be set, and the variable can be assigned to the attribute only if it is set to write. For example, when the attribute can be written: expression Modname.the_anwser = 42 is feasible. Use the DEL protocol to delete writable properties, such as Del Modname.the_answer, which removes the The_answer attribute from the modname.

Namespaces are generated at different points in time and have different limitations. namespaces that contain built-in functions are created when the interpreter is run and are never deleted. The module's global variables are created when the module definition is introduced, and the same namespace will persist as the interpreter is closed. All the protocols that are first executed by the interpreter, whether running scripts or interacting patterns, are considered part of the __main__ module, so they have their own namespaces. (In fact, all of the built-in variable names are also in a module called builtins)

The namespace of the function is local (it can only be called by itself), which is generated when the function is invoked, and ends after the function returns or causes an unresolved exception. Of course recursive call functions they all have their own namespaces.

The Action area (scope) is used to specify that the program can enter those namespaces in those areas, although the action area is statically defined, but is used dynamically, at any point in the execution of the task, there are at least three nested areas of the namespace that can be accessed directly:

The most inner area-the first to be searched, the regions that contain local variables that are implanted--they start with the nearest area, and contain the rest of the nonlocal and Non-global variables--the outermost region of the global variable that contains the current module--and are searched, including the built-in variables that want to reset variables outside the outermost region, You need to use the Nonlocal protocol to define this protocol. If you are not using a variable defined by the Noncocal protocol, then when you want to modify it in the most inner area, you define a variable with the same name in the most inner area, and then assign it to him. But the true variable value does not change, so this should be noted:

In fact, this rule and C language is similar, is in the scope of constantly looking for the outer layer. The global protocol declares that the variable is a global variable, where the new variable is not created in the current scope when and where it is rebind; nonlocal indicates that the variable is in the space of an implanted function and is rebind at the current position. 9.2.1 Scopes and namespaces Example

Let's take a look at a more detailed example:



Note that the assignment in local is not modifying the variable in Scope_test (), and nonlocal modifies the variable. Global variables are modified to be globally variable and can be directly understood to be the namespace of the module. 9.3 A in Classes

This section will introduce some new syntax, and three new types. 9.3.1 Class Definition Syntax

Let's look at one of the simplest ways to declare a statement:


The definition of a class appears to be similar to the definition of a function, which needs to be defined in use, a class can be defined within a function, or a function can be defined in a class. We generally define functions in the class while we practice, but we can remember other protocols as well. The functions defined in the class may have some strange parameters, which are determined by the protocol that invokes the method, which we'll talk about later.

When a new class is defined, a new namespace is created as a range of local variables. In fact, the name of the function also exists in this namespace. When the definition of a class ends normally, a new object type appears. The space of the local variable is then restored to the one before the definition class. 9.3.2 Class Objects

Class objects have two operations, reference the properties of the class, and create a class instance. The syntax for referencing a property is as much a point syntax as a general reference syntax, such as Obj.name. All properties that can be referenced effectively are saved in the namespace when the class is created, so if we define a class like this:


In the example above, myclass.i and MYCLASS.F are valid references that return an integer number and a function object, respectively. Of course can be called can be modified, there is an available attribute __doc__, which holds your description of the class, as to how to write the description we have introduced before. Some methods of creating instances of a class are similar to calling a function, pretending that the function has no arguments, and returning the class instance: x = MyClass () so that we create an instance and the name is X. In general, we create classes to implement specific functions, so when we generate a class instance we want it to contain something as we wish, and this time we can use the __init__ method:

When a class object contains __init__ methods, this method is run every time a new class instance is created. Of course, this method can be used very flexibly, for example, we can pass parameters to it:

9.3.3 Instance Objects

Next, let's look at what we can do with the class strength. You must use a class instance to refer to a property, whether it is a method or a variable within an object. Remember that the object's variables are not required to be declared, they can be assigned directly, and this is the same with the general variables:

The method in the class instance is called the same as the normal function, as long as it is prefixed with the name of the instance. But be aware of distinguishing between instance methods and class methods, which will be mentioned later. 9.3.4 Method Objects

Usually we use the instance name point method name, such as the X.F () in the MyClass example, when using the method of the instance. But this method is also an object, so you can point him to a variable for easy use:

This code will keep printing Hello world until the end of time or the process is closed. What happens when a method is called. In fact, you can already guess that when you call the method of an instance object, you first pass the instance object as a parameter, which means that the X.F () We call is the equivalent of MYCLASS.F (x). If the invoked method accepts the arguments, the arguments are queued and then passed. If you still do not understand it does not matter, you can see the implementation section. When an instance's property (a non variable property) is invoked, he searches the class object first. In fact, the method object is a very abstract object, he is the function object and instance object together and then pass the parameter as a list to him. 9.3.5 Class and Instance Variables

The instance variable is mainly for the characteristics of the data, and the class variable is the attribute of the whole class. Oddly enough, it's easy to see an example that's defined in a different place:


As we said earlier, if the shared data is modifiable, it will have some magical effects, looking at two examples:





This example vivid description of the class variables and instance variables are not, in the use of the time must be clear to their purpose and then design. 9.4 Random Remarks

Variables and methods If there is a conflict with the same name, the text says that the variable attribute will refactor the method attribute, but I experimented with the discovery as if it were just the opposite. In a large program in order to avoid those difficult to find errors, it is best to use a named protocol. For example, uppercase method name, a special character before data property name, or use verb as method name, use noun as variable name.

Variable properties can be called by the same method and by the user, in other words, the class does not implement a completely abstract type. In fact, there's nothing in Python to hide the data-it's based on protocol. Python, on the other hand, uses C to completely hide the details of the implementation and to control the access classes.

Users must be careful when using variable attributes, because some variable attributes are maintained by the method, and user modification directly can cause confusion. So users can add their own variable attributes to an instance, which doesn't affect the method (note that there are no naming conflicts). The visible naming agreement really reduces a lot of headaches.

There is absolutely no shorthand for referencing variable attributes or other methods within a module .... Because this will increase the readability of the code, such a glance will not confuse local variables and instances of variable properties ~

In general, the first parameter of the method is self, which is just a protocol. Self does not have any other special meaning. Anyway, if you don't follow this protocol, other programmers may find it hard to read your code. and a class of browsers is likely to rely on this agreement to work.

The function object for each class provides the method property for an instance of the class, but does not enforce that the definition of the function must be within the declaration of the class. You can assign a function object to a local variable in a class:


In this example, F,h,g are attributes of Class C, and they are also methods of Class C instance variables. The H and G here are exactly the same, and it should be noted that there is no other advantage than reducing readability. Method can also invoke other methods in the instance:


A method can also use a global variable like a function, and a method that invokes the scope of a global variable is the module that defines it. In general, there is no need for methods to use global variables, but there are several things that are more appropriate: a situation where the method can use the functions and modules that are introduced; Typically, the class contains methods that are defined in its own global scope, and in the next chapter we see why a method references its own class. Each variable is an object, so they are also a class that he is used as a object.__class__. 9.5 Inheritance

Of course, since the class is definitely to support the inheritance, or I am sorry that the name. The syntax of a derived class is generally this:


Baseclassname must be defined in the definition scope of a derived class (for example, we do a derived class that inherits from the list, because the list itself is defined in the global variable of the interpreter, so it is OK to define the derived class directly in the interpreter). It is useful to write arbitrary expressions in the base class name section, such as the base class in another module:


When a derived class is created, Python remembers his base class, which is defined to use the attributes of the class. When a property of a class is referenced, it is searched in the base class without being found in the current class, which is recursive, i.e. if the base class is not in the parent class of the base class (if he has a parent class).

An instance of a derived class is nothing special, and the generic class is the same. The method reference is this: first look for a consistent attribute, and if necessary, look in the base class and return a function object if a valid method is found. A derived class can override a method of a base class because the method has no precedence when calling other methods in the same object, so a method in a base class might call a method of a derived class when it calls another method in the base class.

A refactoring approach actually wants to extend new functionality rather than simply substituting the name of the base class method. Calling the base class method is simple: Write Baseclassname.methodname directly (self, arguments). This is sometimes useful for users as well. Note that Baseclassname must be accessible, that his scope must be accessible.

Python has two built-in functions to participate in inheritance-related work:

Use Isinstance (obj, instance) to check that instance is not an instance of the Obj class. Returns true if it is, not returning false. The __class__ property of each instance contains which module the instance belongs to and which type. Use Issubclass (subclass, BaseClass) to check that subclass is not a subclass of BaseClass. Returns TRUE, not returns false.9.5.1 Multiple InheritancePython supports multiple inheritance by defining the following methods:
The main note is to find the order of the attributes, the subclass of their own, needless to say, when looking up the method of the base class in Left-to-right order (in fact, I think if the class design is more reasonable, then do not worry about the problem of name conflict). Note that he will first search a base class until the root, that is, find Base1 did not find will go to Base1 base class rather than to Base2, if the Base1 search to the root is not found will go to Base2 repeat this action. In fact, he might be more complicated than we said, he was using the super () function to achieve dynamic collaboration. This approach is called Call-next-method in other multiple-inheritance languages and is more powerful than the single inheritance feature that uses super. Dynamic sorting is very necessary, because multiple inheritance may have the same relationship as one or more polygons (the lowest class can have multiple channels to access the upper parent class, I choose to use the parent class to describe the fear of confusing the reader with the base class, and my base class is the directly inherited class). For example, all classes inherit from the object class, so any subclass of multiple inheritance has multiple methods for accessing object. In order to prevent the base class from being accessed multiple times, this dynamic meal can be linearized to find the route, let the route guarantee that we set the left to right, ensure that each parent class is only accessed once, and that this route is determined to be monotonous (meaning that a class has a new subclass that does not affect the lookup order of his parent class). By synthesizing these features, we can make multiple inheritance reliable and extensible. More content to see https://www.python.org/download/releases/2.3/mro/This document about method lookup order is too long and I have time to translate it alone.9.6 Private VariablesThere is no private variable in Python that can only be accessed by the instance itself. But we set a protocol for the private variable: A variable that starts with an underscore is treated as a non global variable (whether he is a function method or a data). This is considered to be an implementation detail and will not prompt his changes. Because class private members are really useful, all processes that have a name mangling are limited to support this feature. Any identifier similar to __spam (beginning with a two underscore, with at most an underscore ending) is replaced with a textual _classname_spam, the classname is the name of the current class. The location of this identity is not important, as long as it occurs in the definition of the class. The name processing process can override the method without affecting the method invocation within the class:
In this example, the neutron class, when initializing an instance, invokes the Update method of the parent class, but it itself adds new functionality to the Update method and does not change the name. The plain thing is that private members do not inherit from the quilt class. The purpose of these rules is primarily to avoid accidental occurrences, but it is also possible to modify a private member. This is useful in some situations, such as debugging. Note that the called Class name in the code passed to exec () and eval () is not considered to be the current class, which is somewhat like the global protocol.9.7 odds and EndsSometimes it is useful to use a structure similar to the C language, and defining an empty class can easily accomplish this task:
Classes can be used to mimic many abstract data types.9.8 iteratorsAs you may have noticed now, objects that contain multiple elements can be cycled with the for protocol:
This approach is simple and clear and convenient, and using iterators in Python is uniform and universal. In the background, the for declaration invokes the ITER () function to handle the object. This function returns an iteration object, and the object defines the __next__ () method to access each element of the original object one at a-a-second. When no more elements are, __next__ () can cause stopiterator exceptions. You can use the built-in function next () to invoke the __next__ () method:
In this example I first used the __next__ () method of the instance object and then used the built-in function next () which is actually the __next__ () method of the object being used. Now that we have a general idea of how the iteration works, we can make our own classes to implement the iterative functions we want. First you define a __iter__ () method to return an iterative object, and if the class itself already has a __next__ () method, then the return itself can:

9.9 GeneratorsGenerators (generator, I really don't know why to call such a clumsy name) is a tool that can generate iterators quickly. They look the same as normal functions, but use the yield protocol to return data. Every time he calls the next () function, the generator restarts from where it was last interrupted (he remembers the final protocol and data). The generator is well built. Let's look at a simple example:

What all generators can do, the classes we learned in the last section can do with iterators. The reason the generator is so small is because he automatically generates the __ITER__ () and __next__ () methods. Another key feature is that both local variables and execution protocols are automatically saved between calls. The function is also easy to write, and the local variable is more readable than the Self.index instance variable. And when the generator is over, he will automatically cause stopiterator anomalies. These features make it easier for generators to create iterators.
9.10 Generator ExpressionsSome simple generators can be written using an expression, just like the list derivation we saw before, but this time we don't use square brackets but parentheses. The generator is used directly by the function in the expression, although the generator expression is more concise, but the function and diversity are inferior to the normal generator protocol, but he is more friendly in memory usage than the list derivation of the same function:

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.