PYTHON__ Advanced: __getattribute__ Methods for classes

Source: Internet
Author: User

Tag: UNC LSE Item function code CEE recursive maximum result

In the class, there is no way this thing, all things are stored in the attribute, the so-called call method is actually a class inside the name of a property pointed to a function (method), the return is a function of the reference, and then use the function () this way can call it

When invoking the method of an instance, it is actually a string that passes through the object.

For example, T = Test (), assuming that Func is a method of the Test class, then T.func () is passing a ' func ' string to the class's __getattribute__ method, and after processing it returns a reference to the Func function, and finally F UNC () calls this function (method)

classtest:def __init__ (self): SELF.A= -self.b= $def __getattribute__ (self, item):ifitem = ='a': Print ('------%s------'%Item)return '%s is get'%ItemElse:            return Object. __getattribute__ (self, item) T=Test () print (T.A)>>>------a------a is Get

Whether you invoke a property or a method, you first force the call to the __getattribute__ method, and then return the value of the property or a reference to the function (method).

note that in the __getattribute__ method it is a bad behavior to use a similar self.***, because each invocation of the class's properties forces the call to __getattribute__. Therefore, it is very possible to cause recursive calls.

classtest:def __getattribute__ (Self, item):ifitem = ='a': Print ('------%s------'%Item)return '%s is get'%ItemElse:            returnSelf.test # <----------------------------------------------------------------------------def test (self): Print ('.........') T=Test () print (t.b)>>>recursionerror:maximum recursion depth exceededinchComparison

Self.test will call __getattribute__ again, and the end result is a recursive exception: the maximum recursion depth exceeds what ....

PYTHON__ Advanced: __getattribute__ Methods for classes

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.