python--Special Methods

Source: Internet
Author: User

The functions that begin and end with double underscores in Python are called special functions, and Python automatically views the special methods of invoking these instances when it performs some specific operations on the instance, making it easy to implement overloading of operators in Python.

There are some common special functions in Python:

1. Initialization and termination

__new__ (cls[, args ...])

__new__ () is a static method that is used to create an instance from a type. Python calls the __new__ () method to obtain an instance, invokes the __init__ () method of the instance, and then passes the arguments that were originally passed to the __new__ () method to the __init__ () method.

__init__()

__init__ () is an instance method that is used to perform the necessary initialization after the instance creation is complete, and the method must return none.

Python does not automatically invoke the __init__ () method of the parent class, which requires additional calls:

Super (C, self). __init__ ()

To complete.

__del__ (self)

Before the GC, Python would call this object's __del__ () method to complete some finalization work. If there is no __del__ () method, then Python does not do special processing;

Python ignores the return value of the __del__ () method;

Python does not automatically invoke the __del__ () method of the parent class unless explicitly called;

An instance that defines the __del__ () method cannot participate in a cyclic GC, so a circular reference should be avoided for such an instance;

try/finally statements or with statements may be a better way than __del__ ().

2. Presentation form

__repr__ (self)

Python's built-in repr () function, the ' x ' expression form, or the interactive interpreter invokes the __repr__ () method of the object when displaying the result of an expression statement;

The string returned by the __repr__ () method is primarily for the interpreter, and the rewritten words should satisfy: eval (repr (x)) = = x .

If __repr__ () is not defined, then Python uses a default representation.

__str__ (self)

Python built-in 1. STR () function, 2. The print (x) statement invokes the object's __str__ () method;

Unlike the exhaustive, accurate, unambiguous object description string returned by __repr__ (), the __str__ () method simply returns a concise string representation of the corresponding object;

When __str__ () is missing, Python calls the __repr__ () method;

The string returned by __str__ () should be user-oriented and readable.

__unicode__ (self)

The python built-in Unicode (x) method invokes the __unicode__ () method;

If the method is defined, the priority level is higher than the __str__ () method;

Also define the instances of both methods, and the result of calling them should be the same.

3. Comparing, hashing, and Boolean values

__lt__(self, other)

The x<y operation will invoke the __lt__ (self, the other) method of instance X;

__le__(self, other)

The x<=y operation will invoke the __le__ (self, the other) method of instance X;

__gt__(self, other)

The x>y operation will invoke the __gt__ (self, the other) method of instance X;

__ge__(self, other)

The x>=y operation will invoke the __ge__ (self, the other) method of instance X;

__eq__(self, other)

The x==y operation will invoke the __eq__ (self, the other) method of instance X;

__ne__(self, other)

The x!=y operation will invoke the __ne__ (self, the other) method of instance X;

* The special method used for comparison between instances should return true or FALSE, or return notimplemented to tell the Python interpreter to compare it in other ways.

__cmp__(self, other)

For the comparison operation mentioned above, if the corresponding special method does not define or return notimplemented, then __cmp__ (self, another) will be called to try again;

Some built-in methods: CMP (x, y), Max (x, y), or the sort () method of the list object also calls the __cmp__ () method;

When implementing the X.__cmp__ () method, if x is less than Y, it should return-1, if x is greater than Y, it should return 1, or 0 if x equals Y.

For serialization comparisons (<, <=, >=, >), if the final __cmp__ () is not defined, then an exception is thrown;

For a comparison of equality or not (= =,! =), if the final __cmp__ () is not defined, it will become an identity check: the ID (x) = = ID (y) is set.

__hash__(self)

There are three scenarios in which the __hash__ () method is called: 1. Built-in hash () method, 2. As a dictionary key, 3. When a member of a collection;

The __hash__ () method should return a 32-bit long integer to the same object, and the __hash__ () method should always return the same value, for x = = y , even if they are not of the same type, as long as they are hash (hashable), Should be sure to get hash (x) = = Hash (y) ;

There are no __hash__() methods, and no __cmp__( ) and __eq__() methods, the three cases mentioned above will use the ID (x) As an alternative;

There is no __hash__ () method, but there are __cmp__() and __eq__() methods, and the first two methods mentioned above will throw an exception;

The __hash__ () method is typically defined only for immutable (immutable) objects that define both the __cmp__ () and/or __eq__ () methods.

  

__nonzero__(self)

When determining whether an object is true or false, such as when calling the bool (x) method, Python calls the x.__nonzero__ (self) method, and the __nonzero__ () method should return true or false.

If the instance does not have a __nonzero__ () method, Python invokes the __len__ () method of the instance, and when the __len__ () method returns 0 o'clock, Python considers the object to be false. So if the instance does not have the __nonzero__ () method and the __len__ () method, then Python thinks the instance is always true;

* Therefore, if a container is not empty to determine the condition, it should be written as:

if Container: Pass

Instead of:

if len (container) > 0:  pass

Because the latter will miss the test of the __nonzero__ () method.

4. Referencing, binding, and unbinding a property

__getattribute__ (self, name)

Python automatically calls the x.__getattribute__('y') method when accessing the object's property x.y;

The __getattribute__ () method should return the value of the property being accessed or throw an exception attributeerror ;

The __getattribute__ () method of the overwrite type causes the instance's property access to become slower.

__getattr__ (self, name)

Python calls __getattr__ when a regular property access ( x.__class__ or x.__dict__ key access) cannot be found for the target property () method;

If the method does not find the target attribute, the attributeerror should be thrown.

__setattr__ (self, name, value)

When a property (assignment) of an instance is bound, such as x.y = value , Python automatically calls x. __setattr__('y', value ) method;

Python ignores the return value of the __setattr__() method;

If the __setattr__() method is not defined, Python assigns the value x.y = value to x.__dict__[' y'] = value .

__delattr__ (self, name)

The x.__delattr__('y') is called when a property of an object is unbound (for example, a call to Del x.y). method;

Python ignores the return value of the __delattr__ () method;

If the __delattr__ () method is not defined, then Python interprets del x.y as del x.__dict__[' y'] .

5. Callable Objects

__call__(self[, args ...])

An object that defines the method can be called as a function, so it is called a callable object.

Ii. Special methods of containers

A container can be a sequence (sequence) or a map (mapping)

__contains__(self, item)

The Boolean test y in x calls x.__contains__(y) ;

For sequence x, if y equals one of the values in X, then the __contains__ () method should return true;

For map x, if y equals one of the keys in X, then the __contains__ () method should return true;

If the __contains__ () method is not defined, then the test y in x is equivalent to:

 for inch x:     if y = = z        :return  True    Else        :return False

__delitem__(self, key)

Unbinding an item or slice from a container (such as del X[key] ) invokes the x.__delitem__(Key) method,

Only mutable objects should define this method.

__getitem__(self, key)

The x.__getitem__(Key) method is called when you call X[key] (index or slice);

__iter__(self)

For requests that attempt to traverse all elements of a container (for example, for i in x ), Python will call x.__iter__() To get an iterator on X;

Python built-in functions iter (x) also calls the x.__iter__() method;

If the __iter__ () method is not defined, then the ITER (x) method synthesizes and returns a new iterator that contains X, and then returns the elements in x one after the other;

It is best to implement the __iter__ () method in each container.

  

__len__(self)

The python built-in len (x) call or other function that attempts to know the number of elements in X will eventually call x.__len__() ;

The __len__ () method should return the value of shaping;

When __nonzero__ () is not defined, Python also calls the __len__ () method to determine whether the container is true or false;

Containers should define the __LEN__ () method unless it is particularly expensive to implement.

  

__setitem__(self, key, value)

When you bind an element or slice of a container (for example: X[key] = value ), Python invokes x.__setitem__(key, value) ;

The variable (mutable) container should define the method.

python--Special Methods

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.