_ Getattr _ and _ getattribute _ usage in python

Source: Internet
Author: User
Tags in python


Define the difference:

When __getattr__ (self, item) gets the properties of an instance, it is invoked only if the item is not included in the instance property. This method should return the corresponding property value or throw the Attributeerror exception

__GETATTRIBUTE__ (self, item) Gets the instance property, calls the method unconditionally, regardless of whether the item is included in the instance property


Application examples
1. Using __getattr__ combined with recursion to implement the URL dynamic generator, the code from the Github-sinaweibopy

Class Urlgenerator (object):
def __init__ (self, Root_url):
Self.url = Root_url

def __getattr__ (self, item):
If item = = ' Get ' or item = ' Post ':
Print (Self.url)
Return Urlgenerator (' {}/{} '. Format (Self.url, item)


Url_gen = Urlgenerator (' http://xxxx ')
Url_gen.users.show.get
Http://xxxx/users/show
2. In your own Django project, combine __getattribute__ and decorator to achieve dynamic acquisition of properties.

myconf = Myconfclient ()

def myconf_decorator (key):
"""
First get the attribute key from the myconf, and then go to the Origin_class fetch
"""
def wraper (Origin_class):
# __getattribute__ method for defining the decorated class Origin_class
def __getattribute__ (self, item):
Try
# get the property first from the myconf
return Myconf.get_dict (key) [item]
Except (Cannotgetconferror, Keyerror):
Try
# When the attribute key does not exist in myconf, then look for it from the Origin_class
Return Self.item
Except Keyerror:
Raise Cannotgetconferror (' key:%s item:%s '% (key, item)
origin_class.__getattribute__ = __getattribute__
Return Origin_class ()
Return Wraper
In the process of writing this adorner, there is an infinite recursive situation!!

Recursionerror:maximum recursion depth exceeded while calling a Python object


__getattribute__ Infinite recursion
__GETATTRIBUTE__: will be called unconditionally. When accessing properties of any object, an implicit call to the __getattribute__ method, such as calling T.__dict__, actually executes the t.__getattribute__ ("__dict__") method.

For example, the existence of a class a,a is an instance of a, and when we get the property value through a.x, the actual process:

If __getattribute__ is overloaded in Class A, call __getattribute
No overloaded __getattribute__, call A.\__dict__[x]
Call a.\__dict__[x] or a.\__base__.__dict[x]
So according to the above, we call the __getattribute__ method when a.x, and the method uses Self.key, which is equivalent to calling __getattribute__ again, resulting in infinite recursion. Or if we call __dict__ in the overloaded __getattribute__, we also have infinite recursion.

So, the solution, in the __getatribute__ method, is to call the object.__getattribute__ and cut the infinite recursion:

def __getattribute__ (self, item):
Try
# get the property first from the myconf
return Myconf.get_dict (key) [item]
Except (Cannotgetconferror, Keyerror):
Try
# When the attribute key does not exist in myconf, then look for it from the Origin_class
Return super (Origin_class, self). __GETATTRIBUTE__ (item)
Except (Keyerror, Attributeerror):
Raise Cannotgetconferror (' key:%s item:%s '% (key, item)
And if there is no overloaded __getattr__ method, the __getattribute__ method needs to handle the Attributeerror exception

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.