Object protocol for Python

Source: Internet
Author: User

Python is a dynamic language, Duck typing concepts throughout, so the concept is not based on the constraints of the type as a carrier, but the use of the concept as a protocol. So what is duck typing?

Duck typing is a type of duck, used in dynamic language, is a style of dynamic type language design. In this style, an object's effective semantics are determined not by inheriting from a particular class or implementing a particular interface, but by the collection of current methods and properties. To be blunt is not to care about the type of object, but the behavior.

The name of the concept derives from the duck test presented by James Whitcomb Riley (see the "History" section below), which the "duck test" can say:

"When you see a bird walking like a duck, swimming like a duck and barking like a duck, the bird can be called a duck." ”

In duck type, the focus is not on the type of the object itself, but how it is used.

Look at the following example:

#coding =utf-8class duck:def Quack (self): print U "Quack! "Def Feathers (self): print U" This is a duck. "Class Person:def Quack (self): print U" hello,world! "Def Feathers (self): print U" this is human. "Def in_the_forest (Duck): Duck.quack () duck.feathers () def game (): Donald = Duck () John = person () In_the_fo Rest (Donald) In_the_forest (John) game ()

Running results do not have to be posted, all know what. So how does the above code reflect the duck typing style?

Look at the In_the_forest () function, which has only two requirements for its parameters, that is, this parameter must have quack () and feathers () two methods, regardless of what type it is, as long as there are two methods, can be used as parameters of the in_the_forest () function , and both the class duck and the person implement this method, so their instances can be used as arguments to the in_the_forest (). This is the duck type, not the object type itself, only concerned about behavior. This is more C + + or very different, I also learned C + +, also understand C + + polymorphism and virtual function so the feeling of the difference is quite large.

Now look at what the protocol is, simply put, in Python I need to invoke one of your methods, you happen to have this method, this is the protocol, for example, in addition, when the plus sign (+) appears, then according to the value type of the protocol, Python will automatically call the corresponding object's __add__ ( ) method, which is the protocol.

There are many protocols in Python, such as the following code:

#coding =utf-8a = 1print dir (a)

The results are as follows:

[' __abs__ ', ' __add__ ', ' __and__ ', ' __class__ ', ' __cmp__ ', ' __coerce__ ', ' __delattr__ ', ' __div__ ', ' __divmod__ ', ' __doc_ _ ', ' __float__ ', ' __floordiv__ ', ' __format__ ', ' __getattribute__ ', ' __getnewargs__ ', ' __hash__ ', ' __hex__ ', ' __index__ ' ', ' __init__ ', ' __int__ ', ' __invert__ ', ' __long__ ', ' __lshift__ ', ' __mod__ ', ' __mul__ ', ' __neg__ ', ' __new__ ', ' __nonzero ' __ ', ' __oct__ ', ' __or__ ', ' __pos__ ', ' __pow__ ', ' __radd__ ', ' __rand__ ', ' __rdiv__ ', ' __rdivmod__ ', ' __reduce__ ', ' __ Reduce_ex__ ', ' __repr__ ', ' __rfloordiv__ ', ' __rlshift__ ', ' __rmod__ ', ' __rmul__ ', ' __ror__ ', ' __rpow__ ', ' __rrshift__ ' , ' __rshift__ ', ' __rsub__ ', ' __rtruediv__ ', ' __rxor__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __sub__ ', ' __ Subclasshook__ ', ' __truediv__ ', ' __trunc__ ', ' __xor__ ', ' bit_length ', ' conjugate ', ' denominator ', ' imag ', ' numerator ', ' Real ']

In the above code, a is an integer object, we list all the properties of the object, the above list of properties, "__" and the end of "__" is basically the method of object protocol dependency. is not a lot, we can divide them into the following categories:

(1) Type conversion protocol

Type conversion protocol, as the name implies is used to carry out type, such as a=1,a is an integral type, want to turn it into float float, we can:

#coding =utf-8a = 1print type (a) b = a.__float__ () print bprint type (b)

650) this.width=650; "Src=" Http://s4.51cto.com/wyfs02/M02/88/5D/wKioL1fzqnzwH3kxAAAb5xZ86lE377.png-wh_500x0-wm_3 -wmp_4-s_3660350945.png "title=" Selection _015.png "alt=" Wkiol1fzqnzwh3kxaaab5xz86le377.png-wh_50 "/>

Of course you can also use the built-in function float ().

In addition to __float__ (), there are __str__ (), __repr__ (), __int__ (), __long__ (), __nonzero__ (), and so on, which are all methods that the type conversion protocol relies on.

Mention here __nonzero__ (), which he uses T to convert the class to a Boolean value. This is usually called when the class is judged and the class is converted to a Boolean value. This method is typically called by a conditional statement such as if. Like what:

#coding =utf-8list1 = []if list1:print "1"

The above code, during execution, invokes the __nonzero__ () method of the List1 object to read if it is not empty, and the word will be converted to false. Suppose that some of the classes do not have a __nonzero__ () method defined, then how will it be judged true or false? At this point the object gets the __len__ () method, and if the method returns a value of 0, it is false.

If a class does not define the __nonzero__ () method, and the __len__ () method is not defined, then all instances of the class are true if judged by If.

For example, look at the following examples:

#coding =utf-8class a:def __nonzero__ (self): print U "defines the __nonzero__ () method" Return 1class b:def __len__ ( Self): print U "does not define the __nonzero__ () method, but defines the __len__ () method" Return 1class C:passif A (): A = 1 print AIF B () : A = 2 print AIF C (): a = 3 print a

The results of the operation are as follows:

650) this.width=650; "Src=" Http://s4.51cto.com/wyfs02/M01/88/61/wKiom1fzsLezUZRqAAAmngDjIDs276.png-wh_500x0-wm_3 -wmp_4-s_2693163341.png "title=" Selection _016.png "alt=" Wkiom1fzslezuzrqaaamngdjids276.png-wh_50 "/>

Hopefully the above example will help you understand some of the knowledge.


(2) protocol for comparison of size

This protocol relies on the __cmp__ () method, returns a negative value when the two are equal, and returns a positive value instead of 0,self<other. But this return is a bit complicated, and Python defines __eq__ (), __ne__ (), __lt__ (), __gt__ () and other methods to achieve equality, inequality, less than, and greater than the decision. This is also a mechanism for Python to overload support for operators such as ==,!=,<,>, which means that overloading these operators means redefining the corresponding method.


(3) protocol associated with a numeric type

This kind of method is more, mainly is some operation between the numeric value.

Classification
Method Operator/function Description







numeric operators

__add__ + Add

__sub__

- Reducing
__mul__ * By
__div__ / Except
__floordiv__ // Divisible
__truediv__ / True Division
__pow__ ** Power operation
__mod__ % Take surplus
__divmod__ Divmod () Yu, except





Bitwise operators

__lshift__ << Shift left
__rshift__ >> Shift Right
__and__ & And
__or__ | Or
__xor__ ^ XOR or
__invert__ ~ Non -









Operation Assignment

__iadd__ +=
__isub__ -=
__imul__ *=
__idiv__ /=
__ifloordiv__ //=
__itruediv__ /=
__ipow__ **=
__imod__ %=
__ilshift__ <<=
__irshift__ >>=
__iand__ &=
__ior__ |=
__ixor__ ^=

Other

__pos__ + Is
__neg__ - Negative
__abs__ ABS () Absolute


In addition, there is a unique concept in Python: inverse operation . For example A + B, called the __add__ () method of a, if a does not have __add__ () method, but B has, but this writing call b.__add__ () is not right, this time Python has an anti-operation protocol, it will detect whether there is no __radd__ () in B, If any, then a is called for the parameter. Similar to the __radd__ () method, where all numeric and bitwise operations are, the rules are preceded by the prefix R.


(4) Container class protocol

Since it is a container, then there must be query, value, delete, assignment, length and so on a series of action behavior, then there must be a corresponding method corresponding to these operations. Print out the Dir (list) value and the result is as follows:

[' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __delitem__ ', ' __delslice__ ', ' __doc__ ', ' __eq__ ', ' __format_ ' _ ', ' __ge__ ', ' __getattribute__ ', ' __getitem__ ', ' __getslice__ ', ' __gt__ ', ' __hash__ ', ' __iadd__ ', ' __imul__ ', ' __init_ _ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ' , ' __reversed__ ', ' __rmul__ ', ' __setattr__ ', ' __setitem__ ', ' __setslice__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ' ', ' append ', ' count ', ' extend ', ' index ', ' Insert ', ' pop ', ' remove ', ' reverse ', ' sort ']

which

The length, that is, how many objects are in the query container, using the __len__ () method, the built-in function Len () is implemented by this method.

Values, deletions, assignments correspond to __getitem__ (), __delitem__ (), __setitem__ (), and some containers do not have __setitem__ (), such as strings, which should be immutable objects

__ITER__ () implements the iterative protocol, and __REVERSED__ () provides support for the built-in function reversed () to sort.

There is also a member relationship judge in and not in, and the corresponding method is __contains__ ()


(5) Callable Object protocol

Callable objects, which are similar function objects, can make a class instance behave like a function, which makes each function call different . How do you understand this sentence? Let's look at an example.

#coding =utf-8class A (object): Def __init__ (self,name): self.name = name def __call__ (self): print "Don GN something with%s "% (self.name) A = A (' Li lei ') b = A (' Han Meimei ') print a () Print B ()

The results of the operation are as follows:

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M01/88/5E/wKioL1fzxLvz9_mYAAAehdrZUyE354.png-wh_500x0-wm_3 -wmp_4-s_2410674967.png "title=" Selection _018.png "alt=" Wkiol1fzxlvz9_myaaaehdrzuye354.png-wh_50 "/>

Looking at the example above, we can invoke the instance like a function call

An object can simulate the behavior of a function by providing a __call__ (Slef, [, *args [, **kwargs]) method, and if an object x provides the method, it can be used like a function, which means that X (Arg1, arg2 ...) is equivalent to calling X.__call __ (self, arg1, arg2).


(6) Hash protocol

If the object has the __hash__ () method, it represents a hash object. The __hash__ () method supports this built-in function of hash (). As explained in the document, " if an object is hashed, it must be immutable for its lifetime (a hash function is required) and can be compared with other objects (a comparison method is required). Objects with the same value must have the same hash value .

This means that all immutable built-in type T are hashed, such as String,tuple. All mutable built-in types are non-hashed, such as list,dict (that is, there is no __hash__ () method). The dictionary key must be hashed, so tuple,string can do the key, and list cannot do the key.


(7) Context Manager protocol

This has been said in the previous blog post, do not do too much explanation here, can refer to the previous related blog post. http://11026142.blog.51cto.com/11016142/1845862


Object protocol for Python

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.