"Basic Python Tutorial" Reading notes Chapter Nineth Magic Methods, properties, and iterators (top)

Source: Internet
Author: User

Construction method

Creating a construction method in Python is easy. Just change the name of the Init method from simple init to magic version __init__:

>>> class FooBar:

... def __init__ (self):

... self.somevar=42

...

>>> F=foobar ()

>>> F.somevar

42

Passing several parameters to the construction method

>>> class FooBar:

... def __init__ (self,value=42):

... self.somevar=value

...

>>> F=foobar (' This is a constructor argument ')

>>> F.somevar

' This is a constructor argument '

Overriding general methods and special construction methods

The constructor method is used to initialize the state of the newly created object, and most subclasses not only have their own initialization code, but also the initialization code of the superclass. Although the mechanism of rewriting is the same for all methods, it is more likely to encounter special problems when dealing with construction methods than overriding common methods: if the constructor of a class is overridden, then the constructor of the superclass (the class you inherit) is called, otherwise the object may not be initialized correctly.

>>> class Bird:

... def __init__ (self):

... self.hungry=true

... def eat (self):

... if self.hungry:

... print ' Aaah ... '

... self.hungry=false

.. else:

... print ' No thanks '

...

>>> B=bird ()

>>> B.eat ()

Aaah ...

>>> B.eat ()

No thanks

After the bird has eaten, it is no longer hungry. Now consider the subclass Songbird, which adds the behavior of singing:

>>> class SongBird (Bird):

... def __init__ (self):

... self.sound= ' squawk '

... def sing (self):

... print Self.sound

...

>>> S=songbird ()

>>> s.sing ()

Squawk

Because Songbird is a subclass of bird, it inherits the Eat method, but if the Eat method is called, a problem arises:

>>> S.eat ()

Traceback (most recent):

File "<input>", line 1, in <module>

File "<input>", line 5, in Eat

Attributeerror:songbird instance has no attribute ' hungry '

Error: Songbird has no hungry feature. The reason is this: in Songbird, the constructor method is overridden, but the new constructor does not have any code for initializing the hungry attribute. To achieve the desired effect, the Songbird constructor must call its superclass bird construction method to ensure basic initialization. There are two ways to do this: call the unbound version of the superclass construction method, or use the Super function.

Call Unbound Superclass construction method

>>> class SongBird (Bird):

... def __init__ (self):

... Bird.__init__ (self)

... self.sound= ' squawk '

... def sing (self):

... print Self.sound

...

>>> S=songbird ()

>>> S.eat ()

Aaah ...

>>> S.eat ()

No thanks

>>> s.sing ()

Squawk

When you invoke the method of an instance, the self parameter of the method is automatically bound to the instance (this is called the binding method). However, if you call the method of the class directly (such as bird.__init__), then no instance is bound. This gives you the freedom to provide the self parameter you need. Such a method is called an unbound (unbound) method

Using the Super function

The current class and object can be used as arguments to the Super function, and any method that invokes the object returned by the function is called a method of the superclass, not the method of the current class.

>>> __metaclass__=type

>>> class Bird:

...     def __init__ (s ELF):

...         self.hungry=true

...     def eat (self):

...         If self.hungry:

...             print ' aaah ... '

... &n Bsp           Self.hungry=false

...         else:

...   &nbs P         print ' No thanks '

...            

>>> C Lass SongBird (Bird):

...     def __init__ (self):

...         Super (SongBird, Self). __init__ ()

...         self.sound= ' squawk '

...     def sing (self):

...         Print Self.sound

...  

This new version runs the same result as the old version.

>>> S=songbird ()

>>> s.sing ()

Squawk

>>> S.eat ()

Aaah ...

>>> S.eat ()

No thanks

Basic sequence and mapping rules

Sequences and mappings are collections of objects. In order to implement their basic behavior (rules), if the object is immutable, then there are two magical methods that need to be used, and 4 if it is mutable.

__len__ (self): This method should return the number of items contained in the collection. For a sequence, this is the number of elements. For mappings, the number of key-value pairs.

__getitem__ (Self,key): This method returns the value corresponding to the given key. For a sequence, the key should be an integer of 1 0~n-1 (or a negative number as in the following), n is the length of the sequence, and for the mapping, any kind of key can be used.

__setitem__ (self,key,value): This method should store the value associated with key in a certain way, which can then be obtained using __getitem__. Of course, you can define this method only for objects that can be modified.

__delitem__ (Self,key): This method is called when a del statement is used on a subset of objects, and the key associated with the element must be deleted. This method is also defined for modifiable objects (not all objects are deleted, but only those elements that need to be removed).

>>> def checkindex (key):

... if not isinstance (key, (Int,long)): Raise TypeError

... if Key<0:raise indexerror

...

>>> class Arithmeticsequence:

... def __init__ (self,start=0,step=1):

... self.start=start

... self.step=step

... self.changed={}

... def __getitem__ (Self,key):

... checkindex (key)

... Try:return Self.changed[key]

... except Keyerror:

... return Self.start+key*self.step

... def __setitem__ (self,key,value):

... checkindex (key)

... self.changed[key]=value

...

>>> (s=arithmeticsequence)

>>> S[4]

9

>>> s[4]=2

>>> S[4]

2

>>> S[5]

11

The reason for not implementing the __del__ method is that you want to delete an element that is illegal:

>>> del S[4]

Traceback (most recent):

File "<input>", line 1, in <module>

Attributeerror:arithmeticsequence instance has no attribute ' __delitem__ '

This class has no __len__ method, because it is infinitely long.

If an index of an illegal type is used, an TypeError exception is thrown, and if the type of the index is correct but out of range (in this case, negative), a Indexerror exception is thrown:

>>> S[four]

Traceback (most recent):

File "<input>", line 1, in <module>

Nameerror:name ' Four ' are not defined

>>> S[-4]

Traceback (most recent):

File "<input>", line 1, in <module>

File "<input>", line 7, in __getitem__

File "<input>", line 3, in CheckIndex

Indexerror

Subclass lists, dictionaries, and strings

Example----A list with access counts:

>>> class Counterlist (list):

... def __init__ (Self,*args):

... super (counterlist,self). __init__ (*args)

... self.counter=0

... def __getitem__ (self,index):

... self.counter +=1

... return super (counterlist,self). __getitem__ (Index)

...

The Counterlist class relies heavily on its subclass superclass (list) Behavior Counterlist class does not override any method (and append extend, index) can be used directly. In the two overridden methods, the Super method is used to invoke the method of the corresponding superclass, adding only the behavior of the desired initialization counter attribute in __init__, and updating the counter attribute in __getitem__.

>>> c1=counterlist (Range (10))

>>> C1

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> C1.reverse ()

>>> C1

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

>>> del C1[3:6]

>>> C1

[9, 8, 7, 3, 2, 1, 0]

>>> C1[4]+c1[2]

9

>>> C1.counter

2

Counterlist works in many ways and lists, but it has a counter feature (initialized to 0), and each time the list element is accessed, it will increment itself, so after the addition C1[4]+c1[2) is performed, the value is increased two times and becomes 2.

"Basic Python Tutorial" Reading notes Chapter Nineth Magic Methods, properties, and iterators (top)

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.