Python Learning Notes (methods, properties, iterators)

Source: Internet
Author: User

Preparatory work

To ensure that the class is a new class, you should put the _metaclass_=type into the beginning of your module

Class NewStyle (object):
More_code_here
Class Oldstyle:
More_code_here

In this two class Newtype is the new class, Oldtype belongs to the old class, if preceded by _metaclass_=type, then two classes belong to the new class.

Construction method

The construction method is different from its method, and the constructor method is called immediately when an object is created. Creating a Python constructor is a simple answer, as long as the Init method, from the simple Init method, is converted to the magic version of the _init_ method.

Class FooBar:

def __init__ (self):

Self.somevar = 42

>>> F =foobar ()

>>> F.somevar

42

Override a general method and a special construction method

Each class may have one or more superclass (parent class) that inherit the behavior method from the superclass.

Class A:

def hello (self):

print ' Hello. I am A. '

Class B (A):

Pass>>> a = A ()

>>> B = B ()

>>>a.hello ()

Hello. I am A.

Because Class B does not have a Hello method, Class B inherits the Class A, so the Class A Hello method is called.

The most basic way to add functionality to a subclass is to add a method. However, you can also override some superclass methods to customize the behavior of the inheritance. As follows:

Class A:
def hello (self):
Print "Hello,i ' m A."
Class B (A):
def hello (self):
print ' Hello,i\ ' m B. '

>>> b=b ()
>>> B.hello ()
Hello,i ' m B.
>>>

Rewriting is an important element in the inheritance mechanism, which is especially important for a construction method. Look at the following example:

Class Bird:
def __init__ (self):
Self.hungry=true
Def eat (self):
If Self.hungry:
print ' Aaaah ... '
Self.hungry=false
Else
print ' no,thanks! '

----------------------

>>> B=bird ()
>>> B.eat ()
Aaaah ...
>>> B.eat ()
no,thanks!
>>>

This class defines the bird's ability to eat, and once it has eaten once again it will not be hungry, and can be clearly seen through the above results.

Then use the Songbird class to inherit the bird class and add a way to sing it:

Class Bird:
def __init__ (self):
Self.hungry=true
Def eat (self):
If Self.hungry:
print ' Aaaah ... '
Self.hungry=false
Else
print ' no,thanks! '

Class SongBird (Bird):
def __init__ (self):
Self.sound= ' squawk! '
def sing (self):
Print Self.sound

-----------

>>> Sb=songbird ()
>>> sb.sing ()
squawk!
>>> Sb.eat ()

Traceback (most recent):
File "<pyshell#2>", line 1, in <module>
Sb.eat ()
File "f:/python/mydemo/_init_.py", line 5, in Eat
If Self.hungry:
Attributeerror:songbird instance has no attribute ' hungry '
>>>

The exception clearly illustrates the 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.

Two methods are implemented:

Call Unbound Superclass construction method

Class Bird:
def __init__ (self):
Self.hungry=true
Def eat (self):
If Self.hungry:
print ' Aaaah ... '
Self.hungry=false
Else
print ' no,thanks! '

Class SongBird (Bird):
def __init__ (self):
Bird.__init__ (self)
Self.sound= ' squawk! '
def sing (self):
Print Self.sound

--------------------------

>>> Sb=songbird ()
>>> sb.sing ()
squawk!
>>> Sb.eat ()
Aaaah ...
>>> Sb.eat ()
no,thanks!
>>>

A line of code bird.__init__ (self) has been added to the Songbird class. 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). But if the method of the class is called directly, then no instance is bound. This gives you the freedom to provide the self parameter you need (such a method is called an unbound method).

By providing the current instance as the self parameter to the unbound method, Songbird is able to use all the implementations of its superclass construction method, which means that the property hungry can be set.

Using the Super function

__metaclass__=type
Class Bird:
def __init__ (self):
Self.hungry=true
Def eat (self):
If Self.hungry:
print ' Aaaah ... '
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 ()
Aaaah ...
>>> Sb.eat ()
no,thanks!
>>>

Basic mapping and sequence rules

Sequences and mappings are collections of objects.

__len (self) __:

Returns the number of items contained in the collection. For a sequence, this is the number of elements, and for the mappings, this is the amount of the key ~ value pairs

__getitem__ (Self,key):

Returns the value corresponding to the given key

__setitem__ (Self,key,value):

Store value associated with key in a certain way

__delitem__ (Self,key):

Called when a del statement is used on a subset of objects, and the key associated with the element must be deleted

def checkindex (key):
‘‘‘
Will the given key be an acceptable index?
In order to be accepted, the key should be a nonnegative integer, if it is not an integer, it will throw typeerror if it is negative,
The Indexerror is raised (because the sequence is infinitely long)
‘‘‘
If not isinstance (key, (Int,long)):
Raise TypeError
If key <0:
Raise Indexerror

Class Arithmeticsequence:
def __init__ (self,start=0,step=1):
‘‘‘
Initializing an arithmetic sequence
‘‘‘
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
>>> S[6]
13
>>> s[' four '

Traceback (most recent):
File "<pyshell#6>", line 1, in <module>
s[' Four '
File "f:/python/mydemo/_init_.py", line +, in __getitem__
CheckIndex (Key)
File "f:/python/mydemo/_init_.py", line 8, in CheckIndex
Raise TypeError
TypeError
>>> s[-42]

Traceback (most recent):
File "<pyshell#7>", line 1, in <module>
S[-42]
File "f:/python/mydemo/_init_.py", line +, in __getitem__
CheckIndex (Key)
File "f:/python/mydemo/_init_.py", line ten, in CheckIndex
Raise Indexerror
Indexerror
>>>

Subclass lists, dictionaries, and strings

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)

-------------------------

>>> cl=counterlist (Range (10))
>>> CL
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> Cl.reverse ()
>>> CL
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> del Cl[3:6]
>>> CL
[9, 8, 7, 3, 2, 1, 0]
>>> Cl.counter
0
>>> Cl[4]+cl[2]
9
>>> Cl[4]
2
>>> Cl[2]
7
>>> Cl.counter
4
>>>

Property

Accessors are an easy way to get or rebind some features using the names of GetHeight, SetHeight. If you have to take some action when accessing a given attribute, encapsulating state variables like this are important. As follows:

Class Rectangle:
def __init__ (self):
Self.width=0
Self.height=0
def setSize (self,size):
Self.width,self.height=size
def getsize (self):
Return Self.width,self.height

----------------

>>> R=rectangle ()
>>> r.width=10
>>> r.height=5
>>> r.getsize ()
(10, 5)
>>> r.setsize ((150,100))

>>> R.width
150

In the example above, the GetSize and SetSize methods are accessor methods of an imaginary attribute named size, which is a tuple of width and height.

Property function

__metaclass__=type
Class Rectangle:
def __init__ (self):
Self.width=0
Self.height=0
def setSize (self,size):
Self.width,self.height=size
def getsize (self):
Return Self.width,self.height
Size=property (Getsize,setsize)

----------------------

>>> R=rectangle ()
>>> r.width=10
>>> r.height=5
>>> r.size
(10, 5)
>>> r.size=150,100
>>> R.width
150
>>>

In this new version of Retangle, the property function creates an attribute where the accessor function is used as a parameter (first value, then Assignment), which is the life of size. This eliminates the need to worry about how it is implemented, and can handle width, height, and size in the same way.

Static methods and class member methods

A static method definition does not have a self parameter and can be called directly by the class itself

A class method requires a self-like parameter named CLS when it is defined, and a class member method can be called by a specific object of the class. But the CLS parameter is automatically bound to the class's

__metaclass__=type
Class MyClass:
Def smeth ():
print ' This is a static method '
Smeth=staticmethod (Smeth)

def cmeth (CLS):
print ' This is a class method of ', CLS
Cmeth=classmethod (Cmeth)

The techniques for manual packaging and replacement methods seem monotonous, introducing a new syntax called adorners, using the @ operator

__metaclass__=type
Class MyClass:
@staticmethod
Def smeth ():
print ' This is a static method '

@classmethod
def cmeth (CLS):
print ' This is a class method of ', CLS

-------------------

>>> Myclass.smeth ()
This is a static method
>>> Myclass.cmeth ()
This is a class method of <class ' __main__. MyClass ' >
>>>

__getattr__, __setattr__, and his friends.

__getattr__ (Self,name):

Called automatically when the attribute name is accessed and the object does not have a corresponding attribute

__setattr__ (Self,name,value):

Called automatically when attempting to assign a value to an attribute name

__delattr__ (Self,name):

Automatically called when an attribute name is attempted to be deleted

Class Rectangle:
def __init__ (self):
Self.width=0
Self.height=0
def __setattr_ (Self,name,value):
If name== ' size ':
Self.width,self.height=value
Else
Self.__dict__[name]=value
def __getattr__ (self,name):
If name== ' size ':
Return Self.width,self.height
Else
Raise Attributeerror

Iterators

This section makes a discussion of iterators. Only a special method----__iter__ is discussed, and this method is the basis of the iterator rules

Iterator rules

Iteration means repeating things many times---just like you do in a loop. The __iter__ method returns an iterator that is the object that has the next method, and 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.

Here is an example of Gustav, using Iterators as follows:

Class Fibs:
def __init__ (self):
Self.a=0
Self.b=1
Def next (self):
self.a,self.b=self.b,self.a+self.b
Return SELF.A
def __iter__ (self):
return self

----------------

Fibs=fibs ()

>>> for F in fibs:
If f>1000:
Print F
Break


1597
>>>

Get a sequence from an iterator

In addition to iterating over iterators and iterative objects, you can convert them to sequences. An iterator can be used to replace most of the cases where the sequence can be used.

>>> class Testiterator:
Value=0
Def next (self):
Self.value +=1
If Self.value >10:raise stopiteration
Return Self.value
def __iter__ (self):
return self


>>> Ti=testiterator ()
>>> List (TI)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>

Generator Creation Builder

def flatten (nested):
For sublist in nested:
For element in sublist:
Yield element

>>> Nested=[[1,2],[3,4],[5]]
>>> for num in flatten (nested):
Print num


1
2
3
4
5
>>> list (Flatten (nested))
[1, 2, 3, 4, 5]
>>>

Recursive generators

The generator created above only handles two levels of nesting, and in order to handle nesting using two for loops, if you want to handle nesting of any layer? For example, you might need to add a for loop for each layer nesting, but you don't know how many layers are nested, so you have to make the solution more flexible and can now be resolved with recursion

def flatten (nested):
Try
For sublist in nested:
for element in Flatten (sublist):
Yield element
Except TypeError:
Yield nested

-------------------

>>> list (Flatten ([[[[1],2],3,4,[5,[6,7]],8]))
[1, 2, 3, 4, 5, 6, 7, 8]
>>>

When flatten is called, there are two things: the basic situation and the case where recursion is required

In the basic case, the function is told to expand an element in which the for loop throws an TypeError exception that generates an element.

If you are expanding a list, you need special case handling. The program must traverse all the sub-lists and call flatten on them.

There is a problem with the above approach: if AA is a string-like object (String, Unicode, userstring, and so on), then it is a sequence and does not throw typeerror, but you do not want to iterate over such an object.

In order to handle this situation, you must add a check statement at the beginning of the generator. Try stitching the incoming object and a string to see if it will appear typeerror, which is the simplest and fastest way to check whether an object is similar to a string.

def flatten (nested):
Try
Try:nested+ "
Except Typeerror:pass
Else:raise TypeError
For sublist in nested:
for element in Flatten (sublist):
Yield element
Except TypeError:
Yield nested

--------------------

>>> list (Flatten ([' foo ', [' Bar ', [' Baz ']]))
[' foo ', ' Bar ', ' Baz ']
>>>

If Nested+ ' throws a typerror, it is ignored. If TypeError is not raised, the inner try statement throws a TypeError exception of its own.

Generator method

DEF repeater (value):
While True:
new= (yield value)
If new is not none:value=new

---------------------

>>> R=repeater (42)
>>> R.next ()
42
>>> r.send (' hello,world! ')
' hello,world! '
>>>

Another two ways to build the generator:

The throw method (called with an exception type, with optional values and backtracking objects) is used to throw an exception within the generator (in the yield expression)

The Close method, when not used with parameters, stops the generator.

Python Learning Notes (methods, properties, iterators)

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.