Python magic (notes for learning) and python magic

Source: Internet
Author: User

Python magic (notes for learning) and python magic

Some friends may ask, What is the magic method of python and what is the use of the magic method of python,

They are everywhere in Object-Oriented Python. They are some special methods that allow you to add "magic" to the class. They are often named by underscores.

I think the magic is amazing,

At present, our common magic methods can be roughly divided into the following categories:

  • Construction and initialization
  • Class Representation
  • Access Control
  • Comparison
  • Container operations
  • Callable object
  • Pickling serialization
In python, the most common one is _ init __. this is the python constructor, which is the initialization object and defines the initialization value of an object, __new _ is rarely used in practice, but in some open-source frameworks we can use this, __new _ returns an instance, __del__This method represents the destructor, that is, it is called when the object is garbage collection. However, please note that del xThis method may not be executed __str__/ __repr__

These two magic methods are generally put together for explanation. Their main differences are:

  • __str__Emphasize readability, while__repr__Emphasis on accuracy/standards
  • __str__The target audience is the user, and__repr__The target group is a machine, and its results can be executed.
  • %sCall__str__Method, while%rCall__repr__Method
__setattr__

Through this method, the object can be controlled when assigning values to attributes, and all attribute values will pass through it.

It is generally used to check and verify the assignment of certain attributes, for exampleageIt cannot be less than 0, otherwise it is regarded as illegal data.

__getattr__

In this way, many of you are__setattr__It's totally opposite. Actually it's not!

This method is only used to accessNonexistent attributeWill be called. See the example above, becausegenderThe value assignment operation of this field is ignored when the attribute is assigned a value. Therefore, this attribute is not successfully assigned to the object. When accessing this attribute,__getattr__Called and returnedunknown.

__del__

This method is called to delete an attribute of an object. It is generally used when an attribute must exist. Otherwise, subsequent logical operations cannot be performed. This method is rewritten to check and verify the deletion attribute logic.

__getattribute__

This method is rarely used.__getattr__It is easy to confuse. It differs from the former in:

  • __getattr__Access to a nonexistent property is called,__getattribute__Any access property is called

__getattr__Only for Attribute access,__getattribute__Not only access all attributes, but also call Methods

__iter__

Runfor x in objTrigger execution, used to iterate elements in the container.

__contains__

Runx in objIs used to determine whether an element exists in the container.

__reversed__

Runreversed(obj)Is used to reverse the elements of the container. You can implement the specific reverse logic by yourself.

Reflection

__nstancecheck__(self, instance): Check whether an instance is an instance in your defined class.
__ubclasscheck__(self, subclass): Check whether a class is a subclass of your defined class.

Numeric Operators

Just like you can use comparison operators to compare class instances, you can also define the behavior of numerical operators. Fix your seat belt. There are many such operators. For the sake of organization, I have divided them into five categories: unary operators, common Arithmetic Operators, reflection Arithmetic Operators, enhanced value assignment operators, and type conversion operators.

Unary operator

The unary operator has only one operator.

  • _ Pos _ (self)

Perform a positive operation, for example+ Some_object.

  • _ Neg _ (self)

    Negative operations, such-Some_object.

  • _ Abs _ (self)

    Implement built-in absolute value functionsAbs ()Operation.

  • _ Invert _ (self)

    Implement inverse Operators~.

  • _ Round _ (self, n)

    Implement built-in functionsRound ()N is the approximate number of decimal places.

  • _ Floor _ (self)

    ImplementationMath. floor ()Function, that is, rounded down.

  • _ Ceil _ (self)

    ImplementationMath. ceil ()Function, that is, rounded up.

  • _ Trunc _ (self)

    ImplementationMath. trunc ()Function, that is, an integer closest to zero.

Common Arithmetic Operators

Now let's take a look at common binary operators (and some functions), such as +,-, and *, which are easily understood literally.

  • _ Add _ (self, other)

    Implement addition operations.

  • _ Sub _ (self, other)

    Implements the subtraction operation.

  • _ Mul _ (self, other)

    Implement multiplication.

  • _ Floordiv _ (self, other)

    Implementation and use//The integer division of the operator.

  • _ Div _ (self, other)

    Implementation and use/Division of operators.

  • _ Truediv _ (self, other)

    Implementation_ True _Division. This function is only used.From _ future _ import division.

  • _ Mod _ (self, other)

    Implementation%The remainder operation.

  • _ Divmod _ (self, other)

    ImplementationDivmodBuilt-in functions.

  • _ Pow __

    Implementation**Operator.

  • _ Lshift _ (self, other)

    Implement the Left Shift Operator<.

  • _ Rshift _ (self, other)

    Implement the right shift operator>.

  • _ And _ (self, other)

    Implement bitwise AND Operators&.

  • _ Or _ (self, other)

    Implement bitwise OR Operators|.

  • _ Xor _ (self, other)

    Implement bitwise XOR Operators^.

class DictDemo:    def __init__(self,key,value):        self.dict={}        self.dict[key]=value    def __getitem__(self,key):        return self.dict[key]    def __setitem__(self,key,value):        self.dict[key]="key's value is %s"%value    def __len__(self):        return (len(self.dict))dictDemo=DictDemo('key0','value1')print(dictDemo['key0'])dictDemo['key1']='beijing'print(dictDemo['key1'])print(len(dictDemo))class word(str):    def __eq__(self,other):        return len(self)==len(other)w1=word('idshfisdojf')w2=word('sadsadas')print(w1==w2)print(len(w1))class Apple(object):    def __init__(self,name,size):        self.name=name        self.size=size    def __str__(self):        return 'name is {}: size is {}'.format(self.name,self.size)print(Apple('liwanlei','100'))
class Person(object):    def __init__(self,name,age):        self.name=name        self.age=age    def __str__(self):        return 'name :%s, age:%s'%(self.name,self.age)    def __repr__(self):        return "Person( '%s'%s)"%(self.name,self.age)person=Person('leizi','18')print(str(person))#name :leizi, age:18print(repr(person))#Person( 'leizi'18)

 

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.