Python basic tutorial _ study note 11: Magic methods, attributes, and iterators

Source: Internet
Author: User

Magic methods, attributes, and iterators

In python, some names are prefixed with two underscores. It indicates that the name has a special meaning, so never use this name in your own program. In python, the methods contained in a set composed of these names are called magic (or special) methods. If an object implements one of these methods, this method will be called by python under special circumstances, and there is almost no need to directly call them.

Preparations

To ensure that the class is new, put the value assignment statement _ metaclass __= type at the beginning of your module, or subclass the built-in class (actually the type) object (or some other new classes ).

Constructor

Unlike other common methods, constructor calls constructor immediately after an object is created.

It is easy to create a constructor in python. You only need to change the name of the init method from simple init to the magic version _ init.

Among all the magic methods in python, __init _ is the most commonly used one.

Override general methods and special constructor Methods

If A method is called (or an attribute is accessed) in an instance of Class B, but this method is not found in Class B, it will be found in its superclass.

>>> Class:

Def hello (self ):

Print "Hello, I'm ."

>>> Class B ():

Pass

>>> A = ()

>>> B = B ()

>>> A. hello ()

Hello, I'm.

>>> B. hello ()

Hello, I'm.

The most basic way to add a function to a subclass is to add a method. You can also override some superclasses to customize the inherited behavior.

>>> Class:

Def hello (self ):

Print "Hello, I'm ."

>>> Class B ():

Def hello (self ):

Print "Hello, I'm B ."

>>> A = ()

>>> B = B ()

>>> A. hello ()

Hello, I'm.

>>> B. hello ()

Hello, I'm B.

Rewriting is an important part of the inheritance mechanism and is especially important for Constructor methods. The constructor is used to initialize the state of the newly created object. Most subclasses must not only have their own initialization code, but also have super class initialization code. Although the rewrite mechanism is the same for all methods, it is more likely to encounter special problems when dealing with constructor methods than writing common methods:

If the constructor of a class is overwritten, you need to call the constructor of the super class. Otherwise, the object may not be correctly initialized.

Parent class:

>>> Class Bird:

Def _ init _ (self ):

Self. hungry = True

Def eat (self ):

If self. hungry:

Print "Aaaaah"

Self. hungry = False

Else:

Print "No, thanks! "

>>> B = Bird ()

>>> B. eat ()

Aaaaah

>>> B. eat ()

No, thanks!

Subclass:

>>> Class SongBird (Bird ):

Def _ init _ (self ):

Self. sound = 'squawk! '

Def sing (self ):

Print self. sound

>>> Sb = SongBird ()

>>> Sb. sing ()

Squawk!

However, if you call the eat method, an error occurs:

>>> Sb. eat ()

Traceback (most recent call last ):

File" ", Line 1, in

Sb. eat ()

File" ", Line 5, in eat

If self. hungry:

AttributeError: SongBird instance has no attribute 'hungry'

Cause: In SongBird, the constructor is overwritten, but the new constructor does not have any code to initialize the hungry feature. To achieve the expected results, the SongBird constructor must call its super-class Bird constructor to ensure basic initialization.

There are two ways to achieve this:

The unbound version that calls the superclass method;

Use the super function;

Call unbound superclass Constructor

Solution to the problem raised in the previous section:

>>> Class SongBird (Bird ):

Def _ init _ (self ):

Bird. _ init _ (self)

Self. sound = 'squawk! '

Def sing (self ):

Print self. sound

>>> Sb = SongBird ()

>>> Sb. eat ()

Aaaaah

>>> Sb. eat ()

No, thanks!

When an instance method is called, the self parameter of the method is automatically bound to the instance (this is called the binding method ). If you directly call the class method (such as Bird. _ init _), no instance will be bound. In this way, you can freely provide the required self parameter. This method is called the unbound method.

Use super Function

If you do not want to stick to the old version of python, you should use the super function. It can only be used in the new class, but the new class should be used in any case.

The current class and object can be used as parameters of the super function. Any method that calls the object returned by the function calls the superclass method instead of the method of the current class. Then you can directly use super (SongBird, self) instead of using Bird in the SongBird constructor ). In addition, the __init _ method can be called as a common binding method.

Update the Bird example:

>>>__ Metaclass __= type

>>> Class Bird:

Def _ init _ (self ):

Self. hungry = True

Def eat (self ):

If self. hungry:

Print "Aaaaah"

Self. hungry = False

Else:

Print "No, thanks! "

>>> Class SongBird (Bird ):

Def _ init _ (self ):

Super (SongBird, self). _ init __()

Self. sound = 'squawk! '

Def sing (self ):

Print self. sound

>>> Sb = SongBird ()

>>> Sb. sing ()

Squawk!

>>> Sb. eat ()

Aaaaah

>>> Sb. eat ()

No, thanks!

Member access

Although _ init _ is the most important special method mentioned so far, some other methods are also very important.

The basic sequence and ing rules are simple, but if you want to implement all of them, you need to implement many magic functions.

Basic sequence and ing rules

Sequences and mappings are a collection of objects. To implement their basic behavior (rules), if the object is unchangeable, two magic methods are required. If the object is variable, four magic methods are required.

_ Len _ (self): This method should return the number of items contained in the set.

For sequences, this is the number of elements;

For ing, it is the number of key-value pairs.

If _ len _ returns 0 (and _ nozero _), the object is treated as a dummy value in a Boolean variable (empty list, tuples, string and dictionary.

_ Getitem _ (self. key): This method returns the value of the pair with the given key.

For a sequence, the key should be a 0 ~ N-1 integer. n indicates the length of the sequence;

For ing, keys of any type can be used.

_ Setitem _ (self, key, value): This method stores key-related values in a certain way. This value can be obtained using _ getitem. Of course, this method can only be defined for objects that can be modified.

_ Delitem _ (self, key): This method is called when del statements are used for some objects, and element-related keys must be deleted. This method is also Customizable for modified objects (instead of deleting all objects but only some elements to be removed ).

Attribute

The accessor is a simple method. It can use names such as getHeight and setHeight to obtain or rebind some features.

Python can hide accessors to make all features look the same. These features defined by accessors are called properties.

Property Function

In fact, the property function can be called with 0, 1, 2, 3, or 4 parameters. Without parameters, the generated attributes are neither readable nor writable. If only one parameter is called (one value method), the generated attribute is read-only. The 3rd parameter (optional) is a method used to delete a feature. The 4th parameters are a document string. The four parameters of property are called fget, fset, fdel, and doc respectively.

In fact, the property function is not a real function-it is a class with many special methods on its instance.

Static methods and class member Methods

Static methods and class member methods are loaded into Staticmethod and Classmethod objects at creation. The definition of a static method does not have the self parameter and can be directly called by the class itself.

When defining a class method, a parameter similar to self named cls is required. The class member method can be called directly using a specific object of the class. However, the cls parameter is automatically bound to the class.

Decorator. Use the @ operator to list the decorator above the method (or function, to specify one or more decorators (the order in which multiple decorators are applied is different from that in the specified order ).

Static methods and class member methods are not always important in python because they can be replaced by functions or binding methods in most cases.

_ Getattr _, _ setattr _ and their friends

It is possible to intercept access to all features of an object, so that attributes can be implemented using legacy classes. Some magic methods must be used to execute code when accessing features.

_ Getattribute _ (self, name): The feature name is automatically called when it is accessed (only available in new classes ).

_ Getattr _ (self, name): it is automatically called when the feature name is accessed and the object does not have the corresponding feature.

_ Setattr _ (self, name, value): this parameter is automatically called when you try to assign a value to the feature name.

_ Delattr _ (self, name): it is automatically called when you try to delete the feature name.

The _ setattr _ method is called when the involved feature is not size. Therefore, this method must take both aspects into account: If the attribute is size, perform the operation as before; otherwise, use the special method _ dict __, this special method contains a dictionary that contains the attributes of all instances. To prevent the _ setattr _ method from being called again, the _ dict _ method is used to replace common feature assignment operations.

The _ getattr _ method is called only when common features are not found. This means that if the given name is not size and this feature does not exist, this method will cause an AttributeError error. If you want the class to work properly with built-in functions such as hasattr or getattr, The __getattr _ method is very important. If the size attribute is used, the expression found in the previous implementation is used.

Iterator rules

Iterations mean to repeat several times. So far, only sequences or dictionaries have been iterated in the for loop, but other objects can also be iterated: objects that implement the _ iter _ method.

The _ iter _ method returns an iterator. The so-called iterator is an object with the next method. When the next method is called, The iterator returns its next value. If the next method is called, but the iterator has no value to return, a StopIteration exception is thrown.

What is the key to iteration rules? Why not use the list? Because the list is too lethal. If a function can compute values one by one, it is possible that a value is obtained when a value is calculated-instead of getting all values at a time through the list. If there are many values, the list will occupy too much memory. But there are other reasons: the use of the iterator is more general, simpler, and more elegant.

Get the sequence from the iterator

In addition to iterators and iteratable objects, you can also convert them into sequences. In most cases, sequences can be replaced with iterators.

Generator

The generator can help readers write very elegant code. Of course, it is also possible to write any program without using the generator.

A generator is an iterator defined by common function syntax.

Create a generator

Any function that contains the yield statement is called a generator. In addition to different names, its behavior is also very different from that of common functions. This is because it does not return values like return, but generates multiple values each time. Every time a value is generated (using the yield Statement), the function will be frozen: that is, the function is stopped at that point and waiting to be activated. After the function is activated, it is executed from the stopped point.

Recursive Generator

You can use a recursive generator to process any layer loop;

Universal Generator

A generator is a function that contains the yield keyword. When called, the code in the function body is not executed, but an iterator is returned. Each time a value is requested, the code in the generator is executed until a yield or return statement is encountered. The yield statement indicates that a value should be generated. The return statement means that the generator has to stop running (no more is generated, and the return statement can be called without parameters only when used in a generator ).

In other words, the generator is composed of two parts: the generator function and the generator iterator. Generator functions are defined by def statements, including the yield part. The generator iterator is the part returned by this function.

The iterator returned by the generator function can be used as other iterators.

Generator Method

The new attribute of the generator is the ability to provide values for the generator after it starts running.

Simulation Generator

Omitted;

Eight queens Problem generator and backtracking

Generator is an ideal implementation tool for complex recursive algorithms that gradually generate results. If there is no generator, the algorithm needs a semi-finished solution that passes additional parameters, so that recursive calls can be established in this solution. If a generator is used, all recursive calls only need to create their own yield part.

In some applications, the answer must be selected many times. In addition, the program must make choices at every level of recursion rather than just at one level.

Problem

Eight queens question, omitted;

Related Article

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.