Python Magic Method and invocation method

Source: Internet
Author: User

Magic Method Invocation Mode explain
__new__ (CLS [,...]) Instance = MyClass (Arg1, arg2) __new__ is called when an instance is created
__init__ (self [,...]) Instance = MyClass (Arg1, arg2) __init__ is called when an instance is created
__cmp__ (self, other) Self = = others, self > Other, etc. Called at the time of comparison
__pos__ (self) +self Unary plus operator
__neg__ (self) -self unary minus operator
__invert__ (self) ~self Take the inverse operator
__index__ (self) X[self] When an object is used as an index
__nonzero__ (self) BOOL (self) The Boolean value of the object
__getattr__ (self, name) Self.name # name does not exist When accessing a property that does not exist
__setattr__ (self, name, Val) Self.name = Val When assigning a value to a property
__delattr__ (self, name) Del Self.name When you delete an attribute
__getattribute (self, name) Self.name When accessing any property
__getitem__ (self, key) Self[key] When you use an index to access elements
__setitem__ (self, key, Val) Self[key] = val When assigning a value to an index value
__delitem__ (self, key) Del Self[key] When you delete an index value
__iter__ (self) For x in self When iterating
__contains__ (self, value) Value in the self, value is not in the self When you test a relationship by using the in operation
__concat__ (self, value) Self + Other When connecting two objects
__call__ (self [,...]) Self (args) When the "invoke" object
__enter__ (self) With self as x: With statement Environment management
__exit__ (self, exc, Val, trace) With self as x: With statement Environment management
__getstate__ (self) Pickle.dump (Pkl_file, self) Serialization of
__setstate__ (self) data = Pickle.load (pkl_file) Serialization of

Python Magic Method and invocation method

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.