Python Magic Methods-attribute conversions and the presentation of classes

Source: Internet
Author: User
Tags list of attributes
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)

• Convert to integral type, corresponding to int function.

__long__ (self)

• Convert growth int, corresponding to long function.

__float__ (self)

• Convert to floating-point type, corresponding to the float function.

__complex__ (self)

• Convert to complex type, corresponding to complex function.

__oct__ (self)

• Convert to octal, corresponding to the OCT function.

__hex__ (self)

• Convert to 16 binary, corresponding to 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)

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

__coerce__ (self, other)

• A type cast is implemented, 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 will be re-added support, depending on the official. )

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

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:

Class Foo (object):  def __init__ (self, x):    self.x = x  def __int__ (self):    return int (self.x) + 1  def _ _long__ (self):    return Long (self.x) + 1a = Foo (123) print int (a) print long (a) print type (an int (a)) print type (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:

Class Foo (object):  def __init__ (self, x):    self.x = x  def __int__ (self):    return Long (self.x) + 1  def __long__ (self):    return int (self.x) + 1a = Foo (123) print int (a) print long (a) print type (int (a)) print type (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 Operatorclass Foo (object):  def __init__ (self, x):    self.x = x  def __index__ (self):    return self.x + 1a = Foo (Ten) print Operator.index (a)

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

Class Foo (object):  def __init__ (self, x):    self.x = x  def __index__ (self):    return 3a = Foo (' Scolia ') b = [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):    self.x = x  def __index__ (self):    return int (self.x) a = Foo (' 1 ' b = Foo (' 3 ') c = [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 ') b = foo (' 3 ') c = Slice (A, b) Print cd = [1, 2, 3, 4, 5]print D[c]

__coerce__ (self, Other):

code example:

Class Foo (object):  def __init__ (self, x):    self.x = x  def __coerce__ (self, Other):    return self.x, str ( Other.x) class Boo (object):  def __init__ (self, x):    self.x = x  def __coerce__ (self, Other):    return self.x, int (other.x) a = Foo (' 123 ') b = Boo (123) Print coerce (A, B) print coerce (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)

• Define 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)

• Define 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)

• Define 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

Work 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)

• Define 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"). This defines your own numeric or string type.

• Is very meaningful, you may be given some special formatting options.

__hash__ (self)

• Define 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.

• Be aware that __eq__ is usually implemented 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.

• The concept of a ' hash object ' is introduced here, first the hash value of a hash object should be constant over its lifetime, and the hash value means implementing the __hash__ method. Hash objects can be compared, which means implementing __eq__ or

• 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,

• Dictionaries and more.

• 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)

• Define 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)

• Define 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)

• Define 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.

Above this Python magic Method-Attribute conversion and the description of the class is a small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we support the script home.

  • 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.