1. Attribute access Class rectangle: <br/> def _ init _ (Self): <br/> self. width = 0 <br/> self. height = 0 <br/> def setsize (self, size): <br/> self. width, self. height = size # In my opinion, tuple is automatically formed. <br/> def getsize (Self): <br/> return self. width, self. height # Same as above <br/>
This technology is good syntax, But it tightly coupled the program with an accessor.
Function Property can solve this problem: Class rectangle (object): <br/> def _ init _ (Self): <br/> self. width = 0 <br/> self. height = 0 <br/> def setsize (self, size): <br/> self. width, self. height = size <br/> def getsize (Self): <br/> return self. width, self. height <br/> size = property (getsize, setsize) # Before getter, after setter <br/>
Principle: in fact, property is a class that meets the descriptor protocol (this class implements the _ Get __, _ SET _ and _ Delete _ methods)
Test accessor as follows:
R = rectangle ()
R. width = 10
R. Height = 5
R. Size ---> (10, 5)
R. size = 150,100
R. Width ---> 150
In fact, the property function can also use 0, 1, 3, and 4 parameters.
0 -- resulting property is neither readable nor writable
1 -- resulting property is only readable
3 -- 3rd parameters are used to delete an attribute (this method has no parameters)
Four -- 4th parameters are documentation string
The above four parameters are named fget, fset, fdel, and Doc.
Property (fget, fset, fdel, DOC)
The author finally said that the moral is this: with new-style classes, you should use property rather than accessors.
2. Static methods and class methods
Static methods are methods without the self parameter and can be directly called by classes.
The class method uses a CLS parameter similar to self.
Here is a small example:
_ Metaclass _ = type # declare to use the new-style class <br/> class myclass: <br/> def smeth (): <br/> Print 'this is a static method' <br/> smeth = staticmethod (smeth) <br/> def cmeth (CLS ): <br/> Print 'this is a class method of ', CLS <br/> cmeth = classmethod (cmeth) <br/>
In Python 2.4, a new syntax is introduced: decorators
_ Metaclass _ = type <br/> class myclass: <br/> @ staticmethod <br/> def smeth (): <br/> Print 'this is a static method' <br/> @ classmethod <br/> def cmeth (CLS ): <br/> Print 'this is a class method of ', CLS <br/>
The following is a call:
Myclass. smeth ()
---> This is a static method
Myclass. cmeth ()
---> This is a class method of <class '_ main _. myclass'>
Static methods and class methods are not very important in Python because they were not implemented in earlier versions. However, it is very useful in factory functions.
3. _ getattr __, _ setattr __, and friends
_ Getattribute _ (self, name): automatically called when the attribute name is accessed (works correctly on new-style classes only.) # Note: Todo
_ Getattr _ (self, name): it is automatically called when the attribute name is accessed.
_ Setattr _ (self, name, value): this parameter is automatically called when the attribute name is to be assigned a value.
_ Delattr _ (self, name): this parameter is automatically called when the attribute name is to be deleted.
These magic methods are useful when processing multiple attributes, but if you have a choice, though, stick with property.
Example:
Class rectangle: <br/> def _ init _ (Self): <br/> self. width = 0 <br/> self. height = 0 <br/> def _ setattr _ (self, name, value): <br/> If name = 'SIZE': <br/> self. width, self. height = value <br/> else: <br/> # map the member variables to a pair in the dictionary, which is also a magic attribute, avoid the infinite call of _ setattr __< br/> self. _ dict _ [name] = value <br/> def _ getattr _ (self, name): <br/> If name = 'SIZE ': <br/> return self. width, self. height <br/> else: <br/> raise attributeerror # It is important to make your class work correctly with the built-in functions hasattr and getattr <br/>
4. iterators
Objects that implement the _ ITER _ method can be iterated in the for loop like sequences and dictionaries.
The _ ITER _ method returns an iterator, which is an arbitrary object with the next method and can be called but has no parameters. If no return value is returned when the iterator is called, a stopiteration exception is thrown.
! The following is an iterative Class Example:
Class fibs: <br/> def _ init _ (Self): <br/> self. a = 0 <br/> self. B = 1 <br/> def next (Self): <br/> self. a, self. B = self. b, self. A + self. B <br/> return self. A <br/> def _ ITER _ (Self): <br/> return self <br/>
This iteration is used in the for loop below:
Fiber S = fiber S () <br/> for F in fiber S: <br/> if F> 1000: <br/> Print F <br/> Break <br/># The built-in function ITER can obtain the iterator ITER (OBJ) extracts an iterator from an iterable object.
In addition to traversing objects using the iterator, you can also convert them to sequence:
Class testiterator: <br/> value = 0 <br/> def next (Self): <br/> self. value + = 1 <br/> If self. value> 10: Raise stopiteration <br/> return self. value <br/> def _ ITER _ (Self): <br/> return self <br/>...
Ti = testiterator ()
List (Ti) ---> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
5. generators (essentially an iteration)
# The definition below is given in the book: A generator is a function that contains the keyword yield. When called, the generator function returns a generator, which is a special type of iterator.
Making a generator:
Nested = [[1, 2], [3, 4], [5] # A nested list <br/> def flatten (nested ): <br/> for sublist in nested: <br/> for element in sublist: <br/> yield element # All functions that contain yield are called generator, this means that you can "Harvest" multiple variables at a time, instead of returning only one variable at a time by a common function. <br/>
Or
List (flatten (nested ))
---> [1, 2, 3, 4, 5]
Recursive generator :( it can be used to represent a tree structure)
Def flatten (nested): <br/> try: <br/> for sublist in nested: <br/> for element in flatten (sublist ): <br/> yield element <br/> handle T typeerror: # It cannot be iterated. Generally, it has reached the leaf. <br/> yield nested <br/>
More concise call method:
List (flatten ([[1], 2], 3, 4, [5, [6, 7], 8])
---> [1, 2, 3, 4, 5, 6, 7, 8]
There is a hidden danger in the above recursive method. When a string-like object is iterated, because it is a sequence, it will not cause a typeerror exception. (But the string-like object should not be iterated). The following is a safer definition method:
Def flatten (nested): <br/> try: <br/> # Don't iterate over string-like objects: <br/> try: nested + ''# Check whether it can be merged with a string to see if it is a string-like object <br/> using t typeerror: pass # Is a string-like object, skip the remaining Program <br/> else: Raise typeerror # if it is not a string-like object, a typeerror is thrown for the outer layer to capture and yield <br/> for sublist in nested: <br/> for element in flatten (sublist): <br/> yield element <br/> handle T typeerror: <br/> yield nested <br/>
Example:
List (flatten (['foo', ['bar', ['baz'])
---> ['Foo', 'bar', 'baz']
Generators has two total scores: generator function and generator iterator. The generator function is a function that contains yield; the generator iterator is the return value of the generator function, which is used like other iterators.
Def simple_generator ():
Yield 1
...
Simple_generator
---> <Function simple_generator at 153b44> # It is regarded as a function.
Simple_generator ()
---> <Generator object at 1510b0> # brackets are used as a generator.