Learning notes for beginning python from novice to professional 11 :__ magic __

Source: Internet
Author: User
Tags builtin
N magic power

1. Constructor
Class foobar: <br/> def _ init _ (self, value = 42): <br/> self. somevar = value <br/>
F = foobar ('this is a constructor argument ')
F. somevar --->
'This is a constructor argument'

Call the constructor of the parent class in the Inheritance Mechanism
① Call the class constructor of the parent class (unbound)
Class bird: <br/> def _ init _ (Self): <br/> self. hungry = 1 <br/> def eat (Self): <br/> If self. hungry: <br/> Print 'aaaah... '<br/> self. hungry = 0 <br/> else: <br/> Print 'no, thanks! '<Br/>Class Songbird (BIRD): <br/> def _ init _ (Self): <br/> bird. _ init _ (Self) <br/> # initialize hungry in bird. Otherwise, calling hungry in songbird will cause an exception. <br/> self. sound = 'squawk! '<Br/> def sing (Self): <br/> Print self. Sound <br/> 


② Use the super Function
Class Songbird (BIRD): <br/> def _ init _ (Self): <br/> super (songbird, self ). _ init _ () <br/> # super can only work in the new-style class <br/> self. sound = 'squawk! '<Br/> def sing (Self): <br/> Print self. Sound <br/>Super functions are quite intelligent, especially in the case of multiple inheritance.

The authors of this book summarize these two methods: You don't have to understand exactly how it works internally, but you shoshould be aware that, in most cases, it is clearly superior to calling the unbound Constructors (or other methods) of your superclasses.

2. Basic sequence and mapping protocols (Protocol)
About Protocol: where other has ages might require an object to belong to a certain class, or to implement a certain interface, Python often simply requires it to follow some given protocol. in my understanding, it is necessary to make the object have a certain builtin object nature.

_ Len _ (Self ):
Returns the number of elements in sequence and the number of key-value pairs in mapping. If _ Len _ returns zero (provided that _ nonzero _ is not implemented), this object will be treated as false (with empty lists, tuples, strings, dictionaries ).
_ Getitem _ (self, key ):
Returns the value corresponding to the key. The key in the sequence is 0 to n-1 (or negative, as described later), and The ing is the actual key.
_ Setitem _ (self, key, value ):
Can only be used in writable objects
_ Delitem _ (self, key ):

The preceding four protocols are described as follows:
① If the key in the sequence is a negative number, it is the reciprocal from the back, for example, X [-N] = x [Len (x)-N]
② If the key type is incorrect, for example, if string is used as the key in sequence, a typeerror exception is thrown.
③ If the key type of the sequence is incorrect, an indexerror exception occurs.

Example of a custom sequence:

Def checkindex (key): <br/> if not isinstance (Key, (INT, long): Raise typeerror <br/> If key <0: raise indexerror <br/> class arithmeticsequence: <br/> def _ init _ (self, start = 0, step = 1 ): <br/> "" <br/> initialize the arithmetic sequence. <br/> Start-the first value in the sequence <br/> step-the difference between two adjacent values <br/> changed-A Dictionary of values that have been modifi Ed by <br/> the user <br/> "" <br/> self. start = start # store the start value <br/> self. step = Step # store the step value <br/> self. changed = {}# Note: This is a dictionary, so there is no exception in the following store statement <br/> def _ getitem _ (self, key ): <br/> checkindex (key) <br/> try: return self. changed [Key] # modified? <Br/> couldn't keyerror: # Otherwise... <br/> return self. start + key * self. step #... calculate the value <br/> def _ setitem _ (self, key, value): <br/> checkindex (key) <br/> self. changed [Key] = value # store the changed value <br/> 

The usage of this class is as follows:
S = arithmeticsequence (1, 2)
S [4] ---> 9
S [4] = 2
S [4] ---> 2
S [5] ---> 11
Its behavior is like sequence. You can use the [] operator, which is similar to Operator Overloading in C ++.

# The arithmeticsequence class does not define _ delitem __, so del s [4] may cause exceptions.
# S ["four"] will cause typeerror
# S [-42] will cause indexerror
# _ Len _ is not defined in the class, because it is an infinitely long sequence.

# When making this kind of similar builtin class, pay attention to the point that we try to follow the standard. For example, although we use {} dictionary, we still use isinstance (Key, (INT, long) to check whether the key is an integer, because the builtin key can only be an integer.

If the class is inherited from the standard library (this class is called userlist, userstring, userdict), you do not need to write all the methods by yourself. You only need to override the required methods:
Class counterlist (list): # inherited from list <br/> def _ init _ (self, * ARGs): # Why is * added here? <Br/> super (counterlist, self ). _ init _ (* ARGs) # initialize the parent class <br/> self. counter = 0 <br/> def _ getitem _ (self, index): <br/> self. counter + = 1 <br/> return Super (counterlist, self ). _ getitem _ (INDEX) # Call the parent class <br/>
# Here, You can directly use the append, extend, index, and other functions in the list. Use the following functions:
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. Counter ---> 2

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.