Python leads to millions of programmers cheats! Do you know these tricks? 99% Don't know!

Source: Internet
Author: User
Tags arithmetic arithmetic operators bitwise class definition floor division ftp connection readable

The magic of Python is a method that allows you to add "magic" functionality to your custom classes. In the official Python documentation, the introduction or description of these methods is not only fragmented, but also loosely structured. This article makes a systematic comb for the magic method of Python. For beginners or Python pros, there is more or less a bit of help.

The magic of Python is a method that allows you to add "magic" functionality to your custom classes. In the official Python documentation, the introduction or description of these methods is not only fragmented, but also loosely structured. This article makes a systematic comb for the magic method of Python. For beginners or Python pros, there is more or less a bit of help.

Enter the group: 548377875 can get dozens of sets of PDFs Oh!

Brief introduction

What is the Magic method? They are all for python, and there are special methods that allow you to define features that add "magic" in your own definition class. They always use double underscores (such as __init__ or __lt__), but their documents do not show them well. All of these magical methods appear in the official Python documentation, but the content is relatively fragmented and the organization is loosely structured. And you'll find it hard to see an example (although they are well designed and are described in detail in the language reference, which can then be followed by a tedious syntax description, etc.).

To compensate for these flaws in the official Python documentation, the author has compiled this article on Magic method, designed to be used as a tutorial, review, or reference document.

Below, are examples of __init__ and __del__:

From Os.path Import Join

Class FileObject:

"' Wrapping the file object to ensure that the file is deleted when it is closed '

def __init__ (self, filepath= ' ~ ', filename= ' sample.txt '):

# Press FilePath, read and write mode to open a file named filename

Self.file=open (Join (filepath,filename), ' r+ ')

def __del__ (self):

Self.file.close ()

Del Self.file

Using Operators in custom classes

Magic Method Comparison:

Python has a whole bunch of magic methods designed to use operators to implement visual comparisons between objects, rather than awkward method invocations. They also provide a way to override the default Python behavior for object comparisons. The following is a list of these methods and their effects:

__cmp__ (self, other)

__cmp__ is one of the most fundamental of the magical methods. It actually implements all the comparison operator behaviors (<,==,!=, etc.), but it may not work the way you want (for example, whether one instance equals another depends on the criteria for comparison, and whether one instance is greater than the other). If self < Another, that __cmp__ should return a negative integer, or 0 if self = = other, or a positive integer if self > another. It's usually the best definition, without having to define them all at once, but when you need to do all the comparisons with similar criteria, __cmp__ is a great way to save you from repetition and improve clarity.

__eq__ (self, other)

Defines the behavior of the equality operator, = =.

__ne__ (self, other)

Defines the behavior of the inequality operator,! =.

__lt__ (self, other)

The behavior that is less than operator,< is defined.

__gt__ (self, other)

The behavior that is greater than the operator,> is defined.

__le__ (self, other)

Defines the behavior of <=, which is less than or equal to the operator.

__ge__ (self, other)

Defines the behavior of the >=, which is greater than or equal to the operator.

For example, imagine a class definition for a word. We might want to compare the words internally by the default comparison behavior of strings, that is, the dictionary order (through letters), and also to be able to base on some other criteria, such as length or number of syllables. In this example, we sort by the word length, the following gives the implementation:

Class Word (str):

The word class, which is based on the word length.

Def __new__ (CLS, word):

# Note that we used the __new__ because STR is an immutable type,

# so we have to initialize it earlier (at the time of creation)

If ' in Word:

Print "Word contains a space, truncated to the first part"

Word = Word[:word.index (")] # All characters are now before the first space appears

Return str.__new__ (CLS, Word)

def __gt__ (self, Other):

Return Len (self) > len (Other)

def __lt__ (self, Other):

Return Len (self) < Len (Other)

def __ge__ (self, Other):

Return Len (self) >= len (Other)

def __le__ (self, Other):

Return Len (self) <= len (Other)

Magic Method Numbers:

Just as you can create your own class instances by overloading the comparison operators, you can also reload the numeric operators.

Unary operators:

Unary operations and functions have only one operand, such as negative numbers, absolute values, and so on.

__pos__ (self)

The behavior of implementing unary positive numbers (for example: +some_object)

__neg__ (self)

Implement negative behavior (for example:-some_object)

__abs__ (self)

Implementing the behavior of the built-in ABS () function

__invert__ (self)

Implements the inverse behavior with the ~ operator.

Regular arithmetic operators:

Now we cover the basic two-dollar operator: +,-,* and so on. Most of them are self-explanatory.

__add__ (self, other)

implementing addition

__sub__ (self, other)

Implementing subtraction

__mul__ (self, other)

Implement multiplication

__floordiv__ (self, other)

Implement floor division, using//Operator

__div__ (self, other)

Implementing traditional division, using/operator

__truediv__ (self, other)

Achieve true division. Note that it only works if you are from __future__ import division

__mod__ (self, other)

Implementing modulo, using the% operator

__divmod__ (self, other)

Implementing the behavior of the built-in function divmod ()

__pow__ (self, other)

To achieve the exponentiation, use the * * operator

__lshift__ (self, other)

Implement left bitwise displacement, using the << operator

__rshift__ (self, other)

Implement right-click displacement, using the >> operator

__and__ (self, other)

Implement bitwise-AND, use & operators

__or__ (self, other)

Implement a bitwise OR, use | operator

__xor__ (self, other)

Implementing bitwise XOR, using the ^ operator

Reflection Arithmetic operators:

Let's start with an example: Some_object + other. This is the "regular" addition. And reflection is actually equivalent to the same thing, except that the operand changes the position of the next: Other + Some_object. In most cases, the result of the reflection arithmetic operation is equivalent to a regular arithmetic operation, so you can call __add__ as soon as you have finished overloading the __radd__. Simply Jolly:

__radd__ (self, other)

Implementing Reflection Addition

__rsub__ (self, other)

Implementing Reflection Subtraction

__rmul__ (self, other)

Implementing Reflection multiplication

__rfloordiv__ (self, other)

Implement reflective Flooring In addition to//operator

__rdiv__ (self, other)

Implementing traditional division, using/operator

__rturediv__ (self, other)

Achieve true division, note that it only works if you are from __future__ import division

__rmod__ (self, other)

Realization of reflection modulus, with% operator

__rdivmod__ (self, other)

Implements the long-removed behavior of the built-in function Divmod (), called when Divmod (other,self) is called

__rpow__ (self, other)

Implement Reflection exponentiation with * * operator

__rlshift__ (self, other)

Implementing the Left bitwise displacement of reflection, using the << operator

__rrshift__ (self, other)

Implement right-click displacement of reflection, using >> operator

__rand__ (self, other)

Implement the bitwise AND of reflections, using the & operator

__ror__ (self, other)

Implement a bitwise OR of reflection, using the | operator

__rxor__ (self, other)

To implement a bitwise XOR of a reflection, use the ^ operator

Increment Assignment:

Python also has a variety of magical methods that allow users to customize incremental assignment behavior.

None of these methods have a return value, because the assignment does not have any return value in Python. Instead they just change the state of the class. The list is as follows:

__rxor__ (self, other)

implementing Addition and assignment

__isub__ (self, other)

Implementing Subtraction and Assignment

__imul__ (self, other)

Implement multiplication and assignment

__ifloordiv__ (self, other)

Implementation of floor addition and assignment, with//= operator

__idiv__ (self, other)

Implement traditional division and assignment with the/= operator

__iturediv__ (self, other)

Achieve true division and assignment, note that only valid if you are from __future__ import division

__imod__ (self, other)

Implement modulo and assignment, using the%= operator

__ipow__ (self, other)

Implement exponentiation and assignment with the **= operator

__ilshift__ (self, other)

Implement left bitwise displacement and assignment using the <<= operator

__irshift__ (self, other)

Implement right-bitwise displacements and assignments using the >>= operator

__iand__ (self, other)

Implement bitwise AND and assignment using the &= operator

__ior__ (self, other)

Implementing bitwise OR and assignment using the |= operator

__ixor__ (self, other)

Implementing bitwise XOR and Assignment using the ^= operator

A magical way to type conversions:

Python also has a set of magical methods that are designed to implement the behavior of built-in type conversion functions, such as float ().

__int__ (self)

Implementing type conversions to int

__long__ (self)

Implementing a type conversion to a long

__float__ (self)

Implementation of type conversion to float

__complex__ (self)

Implementing a type conversion to a complex number

__oct__ (self)

Implementing a type conversion of 8 binary

__hex__ (self)

Implementing a type conversion of 16 binary

__index__ (self)

Implements a type conversion when an object is sliced into int. If you customize a numeric type, consider that it may be sliced, so you should reload __index__.

__trunc__ (self)

Called when Math.trunc (self) is invoked. __TRUNC__ should return a truncation of an integral type (usually a long).

__coerce__ (self, other)

This method is used to implement mixed-mode arithmetic. If the type conversion is not possible that __coerce__ should return none. Otherwise, it should return a pair containing self and other (2 tuples), and adjust to having the same type.

Describe custom classes

It is often useful to use a string to describe a class. There are several ways in Python that you can customize the built-in functions in your own class to return the description of your class behavior.

__str__ (self)

When you define an instance of a class that calls Str (), it is used to define the behavior for it

__repr__ (self)

When you define an instance of a class that calls Repr (), it is used to define the behavior for it. The main difference between STR () and REPR () is its reading object. The output produced by REPR () is mainly computer readable (in many cases this may even be a valid Python code), while STR () is intended to be human readable.

__unicode__ (self)

When you define an instance of a class that calls Unicode (), it is used to define the behavior for it. Unicode () is like STR (), except that it returns a Unicode string. Alert! If the user calls Str () with an instance of your class, and you define only __unicode__ (), it will not work. Just in case, you should always define __STR__ (), even if the user does not use Unicode.

__hash__ (self)

When you define an instance of a class that calls a hash (), it is used to define the behavior for it. It must return an integral type, and its result is to be used as a fast key pair in the dictionary.

__nonzero__ (self)

When you define an instance of a class that calls bool (), it is used to define the behavior for it. Returns TRUE or false, depending on whether you consider an instance to be true or false.

We've done a pretty good job of doing the boring part of the Magic method (no example), so now we've discussed some of the basics of magic, and it's time for us to move on to advanced topics.

Controlling Property access

Python implements a large number of packages in a magical way, rather than through explicit methods or field modifiers. For example:

__getattr__ (self, name)

You can define a user's behavior when attempting to access a class property that does not exist, whether it exists or has not yet been established. This is useful for snapping and redirecting common spelling errors, given the use of attribute warnings (you can still choose the calculation, return that attribute if you prefer) or throw a Attributeerror exception. This method only applies to accessing a nonexistent property, so this is not a true encapsulation of the solution.

__setattr__ (self, name, value)

Unlike __getattr__,__setattr__, it is a packaged solution. It allows you to assign a value to the behavior of a property, regardless of whether the property exists. This means that you can customize the rules for any changes to the property values. However, what you need to care about is that you should be careful about using __setattr__, which will be given as an example in a later list.

__delattr__

This is equivalent to __setattr__, but as a delete class property instead of set them. It requires the same precautions, like __setattr__, to prevent infinite recursion (when calling del Self.name in __delattr__ will cause infinite recursion).

__getattribute__ (self, name)

__getattribute__ well suited to its companions __setattr__ and __delattr__. But I do not recommend you to use it.

__GETATTRIBUTE__ can only be used in modern classes (in the latest version of Python, all classes are modern, and in a slightly older version you can create a modern class by inheriting the object class.) It allows you to make rules that are accessible at any time regardless of the value of a class property. It will be plagued by some infinite recursion problems due to the error guilt in his companion (you can prevent this by calling the __getattribute__ method of the base class). When __GETATTRIBUTE__ is implemented and only calls the method if __getattribute__ is explicitly called or throws a Attributeerror exception, it also avoids the dependency on __getattr__. This method can be used, but I do not recommend it because it has a small use case (although relatively rare, but we need special behavior to get a value instead of assignment) and it is really difficult to achieve 0bug.

You can easily raise a problem when you customize any class property access method. Refer to this example:

def __setattr__ (self, Name, value):

Self.name = value

# when assigning a value to a class attribute each time, __setattr__ () is called, which forms a recursive

# because what it really means is self.__setattr__ (' name ', value)

# So this method keeps calling itself and becomes a recursive final trigger that cannot be exited crash

def __setattr__ (self, Name, value):

Self.__dict__[name] = value # Assigns a value to the name in the dictionary

# in this custom behavior

Here is a practical example of a special Property access method (Note that we use super because not all classes have the __dict__ class attribute):

Class Accesscounter:

A class contains a value and implements an access counter.

Counter +1 "When the value changes every time

def __init__ (Self, Val):

Super (Accesscounter, self). __setattr__ (' counter ', 0)

Super (Accesscounter, self). __setattr__ (' value ', Val)

def __setattr__ (self, Name, value):

If name = = ' Value ':

Super (Accesscounter, self). __setattr__ (' counter ', Self.counter + 1)

# make this unconditional.

# If you want to prevent other properties from being created, throw Attributeerror (name) exception

Super (Accesscounter, self). __SETATTR__ (name, value)

def __delattr__ (self, name)

If name = = ' Value ':

Super (Accesscounter, self). __setattr__ (' counter ', Self.counter + 1)

Super (Accesscounter, self). __DELATTR__ (name)

Making a custom sequence

There are many ways to make your classes behave like built-in sequences (dictionaries, tuples, lists, strings, etc.). These are my favorite magic methods so far, because unreasonable control gives you a magic way to let your class instances of the entire global array of functions work beautifully.

__len__ (self)

Returns the length of the container. Partial protocol supports both variable and immutable containers

__getitem__ (self, key)

Defines the behavior when an item is accessed, using Self[key] notation. This is also partly variable and immutable container protocol. This can also throw an appropriate exception: TypeError when the type of key is wrong, or if there is no value corresponding to key.

__setitem__ (self, key, value)

Defines the behavior when an item is assigned a value, using self[key]=value notation. This is also a partially variable and immutable container protocol. Once again, you should throw keyerror and typeerror anomalies where appropriate.

__delitem__ (self, key)

Defines the behavior when an item is deleted (for example, Del Self[key]). This is only the protocol of a partially variable container. After an invalid key is used, you must throw an appropriate exception.

__iter__ (self)

You should return an iterator to the container. Iterators return several things, mostly using the built-in function iter (). When a container uses a loop that is shaped like for X in container:. The iterator itself is its object, and the good one __iter__ method is also defined to return itself.

__reversed__ (self)

When defining a call to the built-in function reversed () behavior. A reverse version of the list should be returned.

__contains__ (self, item)

__contains__ is a member relationship, and the behavior is defined with in and not in Tests. So you're going to ask why is this not part of a sequence of protocol? This is because when __contains__ is undefined, Python iterates through the sequence and returns true if it encounters the item being looked for.

__concat__ (self, other)

Finally, you can define your sequence and another sequence of connections through __concat__. A newly constructed sequence should be returned from self and other. When 2 sequences are called __concat__ involves operator +

In our example, let's take a look at some of the basic functional constructs of a list implementation. It may remind you of other languages you use (such as Haskell).

Class Functionallist:

The class covers some of the additional functional magic of a list, like head,

Tail,init,last,drop,and take ' '

def __init__ (self, Values=none):

If values is None:

Self.values = []

Else

Self.values = values

def __len__ (self):

Return Len (self.values)

def __getitem__ (self, key):

# If key is an illegal type and value, then list valuse will throw an exception

return Self.values[key]

def __setitem__ (self, Key, value):

Self.values[key] = value

def __delitem__ (self, key):

Del Self.values[key]

def __iter__ (self):

Return iter (Self.values)

def __reversed__ (self):

return reversed (self.values)

def append (self, value):

Self.values.append (value)

def head (self):

# Get the first element

return Self.values[0]

def tail (self):

# get all the other elements after the first one

Return Self.values[1:]

def init (self):

# Gets the sequence except for the last element

return Self.values[:-1]

Def last:

# get the last element

return Self.values[-1]

def drop (self, n):

# Gets the sequence except for the first n elements

Return Self.values[n:]

def take (self, n):

# get the first n elements

return SELF.VALUES[:N]

Reflection

You can also control how reflection uses the behavior of the built-in functions isinstance () and Issubclass () by defining magical methods. These magical methods are:

__instancecheck__ (self, instance)

Check if an instance is an instance of your defined class (for example, Isinstance (instance, Class))

__subclasscheck__ (self, subclass)

Check if a class is a subclass of your defined class (for example, Issubclass (subclass, Class))

Callable Object

This is a special magic method in Python that allows your class instances to resemble functions. So you can "call" them, pass them as arguments to the function, and so on. This is another powerful and convenient feature that makes Python's programming a little more adorable.

__call__ (self, [args ...])

Allows class instances to be called as functions. Essentially, this means that X () is equivalent to x.__call__ (). Note that the number of arguments required by __call__ is variable, meaning that you can define __call__ for any function that defines the number of arguments you prefer.

__call__ may be extremely useful for instances that often change state. The invoke instance is an intuitive and elegant way to change the state of an object. The following example is a class that represents the position of an entity on a plane:

Class Entity:

"' describes the entity's class, which is called to update the entity's position '

def __init__ (self, size, x, y):

self.x, self.y = x, y

Self.size = Size

def __call__ (self, x, y):

' Change the position of the entity '

self.x, self.y = x, y

#省略 ...

Context Manager

Context management allows you to set and clean up an object and use the with declaration for an already encapsulated operation. The behavior of a context operation depends on the 2 magic methods:

__enter__ (self)

Defines when a block is created with a with declaration, what context management should do at the beginning of the block.

__exit__ (self, exception_type, Exception_value, Traceback)

Defines what context management should do after the block executes (or terminates).

You can also use these methods to create context management that encapsulates the common purpose of other objects. Look at the following example:

Class Closer:

"' declares a context management with a with a close method to automatically close an object"

def __init__ (self, obj):

Self.obj = obj

def __enter__ (self):

Return Self.obj # binding target

def __exit__ (self, exception_type, Exception_val, trace):

Try

Self.obj.close ()

Except Attributeerror: #obj不具备close

print ' Not closable. '

Return True # successfully handled exception

The following is an example of a practical application for closer, using an FTP connection for a demo (a socket that can be closed):

>>> from magicmethods import Closer

>>> from ftplib import:;;

>>> with Closer (FTP (' ftp.somsite.com ')) as Conn:

... conn.dir ()

...

# omitted output

>>> Conn.dir ()

# A very long attributeerror message that cannot be closed using a connection

>>> with Closer (int (5)) as I:

... i + = 1

...

Not closeable.

>>> I

6

Building Descriptor Objects

Descriptors can change other objects, or they can be getting,setting,deleting that access any one of the classes.

As a descriptor, a class must implement at least __get__,__set__, and one of the __delete__. Let's take a quick look at these magical methods:

__get__ (self, instance, owner)

Defines its behavior when the value of the descriptor is retrieved. Instance is an instance of the owner object, and owner is all classes.

__set__ (self, instance, value)

Defines the behavior of a descriptor when its value is changed. Instance is an instance of the owner object, which is the value of the set descriptor

__delete__ (self, instance)

Defines its behavior when the value of the descriptor is deleted. Instance is an instance of the owner object.

Now, there is a useful descriptor application example: unit conversion policy

Class Meter (object):

' M descriptor '

def __init__ (self, value=0.0):

Self.value = Float (value)

def __get__ (self, instance, owner):

Return Self.value

def __set__ (self, instance, value):

Self.value = Float (value)

Class Foot (object):

' ' Foot descriptor '

def __get__ (self, instance, owner):

Return Instance.meter * 3.2808

def __set__ (self, instance, value):

Instance.meter = Float (value)/3.2808

Class Distance (object):

"The class that represents the distance, control 2 descriptors: feet and meters"

meter = meter ()

foot = foot ()

Summarize

The goal of this guide is for anyone to be able to read it, regardless of whether they have Python or object-oriented programming experience. If you are preparing to learn python, you have gained valuable knowledge of writing rich, elegant, easy-to-use classes. If you are an intermediate Python programmer, you may have picked up some concepts, strategies, and some good ways to reduce the amount of code you write. If you are a Python expert, you may have reviewed some of the points you may have forgotten, or you have some new discoveries. Regardless of your level of experience, I hope you get something out of this amazing python journey!

Python leads to millions of programmers cheats! Do you know these tricks? 99% Don't know!

Related Article

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.