Python Magic Methods-attribute conversions and class representations

Source: Internet
Author: User
Tags readable

Type Conversion Magic

Type Conversion magic is actually the result of implementing factory functions such as STR, int, and usually these functions have the function of type conversion, here are some related magic methods:

    • __int__ (self)

    • are converted to integers, corresponding to the INT function.

    • __long__ (self)

    • Convert growth int, corresponding to long function.

    • __float__ (self)

    • is converted to float, corresponding to the float function.

    • __complex__ (self)

    • Convert to   complex, corresponding to complex function.

    • __oct__ (self)

    • is converted to octal, corresponding to the OCT function.

    • __hex__ (self)

    • is converted to 16 binary, corresponding to the hex function.

    • __index__ (self)

    • First, this method should return an integer, either int or long. This method is valid in two places, the first is the value of the index function in the  operator module is the return value of this method, followed by the slicing operation, the following will be dedicated to the code demonstration.

    • __trunc__ (self)

    • is called when Math.trunc is used. __trunc__ returns an integer intercept of its own type (usually a long integer).

    • __coerce__ (self, other)

    • The
    • Implements a type cast, which corresponds to the result of the  coerce built-in function (python3.0 begins to remove the function, that is, the Magic method does not make sense, as to whether the subsequent version of the re-join support, depending on the official.

    • This function is mandatory to convert two different number types into the same type, for example:

#coerce (x, y) (x1, y1)

method returns a tuple that corresponds to the converted two digits. The priority is: complex > Floating-point numbers > Long integer > Integer. At the time of conversion, it is converted to a high-priority type in two parameters. TypeError is triggered when the conversion cannot be completed.

And when we define this magic method, we should return none if the conversion cannot be completed.

Here's an important mechanism, when Python is doing arithmetic, such as 1 + 1.0, it calls the coerce function to convert it to the same type and then runs it, which is why 1 + 1.0 = 2.0, because the actual operation after the conversion is 1.0 +1.0. It is not surprising to get such a result.

code example:

classFoo (object):def __init__(self, x): self.x=xdef __int__(self):returnInt (self.x) + 1def __long__(self):returnLong (self.x) + 1a= Foo (123)PrintInt (a)PrintLong (a)Printtype (int (a))PrintType (Long (a))

One thing to note here is that the return value of the Magic method must be the same as expected, such as __int__ should return an int type, and if we are wayward to return other types, such as String (str), list, etc., the error will be.

    def __int__ (self):         return str (self.x)

    def __int__ (self):         return list (self.x)

But int can return a long, and long returns int when it is automatically processed as long:

classFoo (object):def __init__(self, x): self.x=xdef __int__(self):returnLong (self.x) + 1def __long__(self):returnInt (self.x) + 1a= Foo (123)PrintInt (a)PrintLong (a)Printtype (int (a))PrintType (Long (a))

The above happened on the python2.7.11, this is a very strange behavior, so that I think it may be a BUG, in short we have to pay attention to the use of the corresponding type is to avoid errors.

__index__ (self):

The first is corresponding to Operator.index (), Operator.index (a) is equivalent to a.__index__ ():

Import operator class Foo (object):     def __init__ (self, x):         = x    def__index__(self):        return self.x + 1  = Foo (+)print operator.index (a)

The other is a magical effect, when used in a sequence:

class Foo (object):     def __init__ (self, x):         = x    def__index__(self):        return 3= Foo ( ' Scolia '  = [1, 2, 3, 4, 5]print  b[a]print b[3]

Can be used as an index for slicing operations:

class Foo (object):     def __init__ (self, x):         = x    def__index__(self):        return= Foo (  '1'= Foo ('3'= [1, 2, 3, 4, 5  ]print c[a:b]

In fact, the use of the internal section of the function slice to deal with it, interested students can go to understand this function:

A = foo ('1'= foo ('3'= Slice (A, b) Print  = [1, 2, 3, 4, 5]print d[c]

__coerce__ (self, Other):

code example:

classFoo (object):def __init__(self, x): self.x=xdef __coerce__(self, Other):returnself.x, str (other.x)classBoo (object):def __init__(self, x): self.x=xdef __coerce__(self, Other):returnself.x, int (other.x) a= Foo ('123') b= Boo (123)Printcoerce (A, b)PrintCoerce (b, a)

Summary: Is the Magic method that invokes the first argument .

The representation of the class:

The representation of a class is actually an external feature, such as what is printed when using the print statement, which is essentially the output of the corresponding function:

    • __str__ (self)

    • Defines the behavior to be generated when STR () is called by an instance of your class. Because print is called the STR () function by default.

    • __repr__ (self)

    • Defines the behavior to be generated when repr () is called by an instance of your class. The main difference between STR () and REPR () is its target group.  Repr () returns the machine-readable output, and STR () returns human-readable. The repr () function is called by the swap mode by default

    • Function.

    • __unicode__ (self)

    • Defines the behavior to be generated when Unicode () is called by an instance of your class. Unicode () is similar to STR (), but returns a Unicode string. Note that if you call STR () on your class, but you only define __UNICODE__ (), then it will not

    • Job. You should define __STR__ () to ensure that the correct values are returned when called, and not everyone is in the mood to use Unicode ().

    • __format__ (self, formatstr)

    • Defines the behavior that occurs when an instance of one of your classes is used to format a new format string method. For example,  "Hello, {0:abc}!". Format (a) will cause the call to  A.__FORMAT__ ("abc"). It makes sense to define your own numeric or string type

    • , and you might give some special formatting options.

    • __hash__ (self)

    • Defines the behavior to be generated when a hash () is called by an instance of your class. It must return an integer that can be used for quick comparisons in the dictionary.

    • Note that it is often necessary to implement __eq__ when implementing __hash__. There are the following rules: a = = B implies a hash (a) = = hash (b). This means that the return value of the two magic methods is best consistent.

    • This introduces the concept of a ' hash object ', where the hash value of a hash object should be constant for its lifetime, and a hash value would imply the implementation of the __hash__ method. Hash objects can be compared, which means implementing __eq__ or
    • who The __cmp__ method, and the hash object equal must have its hash value equal, to implement this feature means that the __eq__ return value must be the same as __hash__.
    • A hash object can be a member of a dictionary's keys and collections, because the hash value is used internally by these data structures. All of the built-in immutable objects in Python are hashed, such as tuples, strings, numbers, and so on, while mutable objects cannot be hashed, such as lists,
    • Dictionary and so on.
    • Instances of user-defined classes are hashed by default and are not equal except for themselves, because their hash values are derived from the ID function. But this does not mean hash (a) = = ID (a), pay attention to this feature.
    • __nonzero__ (self)

    • Defines the behavior to be generated when bool () is called by an instance of your class. This method should return true or false, depending on the value you want it to return. (python3.x in __bool__)

    • __dir__ (self)

    • Defines the behavior to be generated when Dir () is called by an instance of your class. The method should return a list of attributes to the user.

    • __sizeof__ (self)

    • Defines the behavior to be generated when sys.getsizeof () is called by an instance of your class. The method should return the size of your object in bytes. This is often more meaningful for Python classes implemented in the form of a C extension, which helps to understand these extensions.

There is nothing particularly difficult to understand here, so the code example is omitted.

You are welcome to exchange.

Python Magic Methods-attribute conversions and class representations

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.