Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relationship between __getattr__ and getattr?

Tags:

python

getattr

I know this code is right:

class A:        def __init__(self):         self.a = 'a'       def method(self):            print "method print"    a = A()    print getattr(a, 'a', 'default')    print getattr(a, 'b', 'default')   print getattr(a, 'method', 'default')  getattr(a, 'method', 'default')()    

And this is wrong:

# will __getattr__ affect the getattr?  class a(object):     def __getattr__(self,name):         return 'xxx'  print getattr(a) 

This is also wrong:

a={'aa':'aaaa'} print getattr(a,'aa') 

Where should we use __getattr__ and getattr?

like image 428
zjm1126 Avatar asked Dec 22 '09 07:12

zjm1126


People also ask

What does __ Getattr __ do in Python?

__getattr__Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self ). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.

What is Getattr bracket used for?

Python getattr is used to get an object attribute value, and if no attribute of that object is identified, the default value is returned. The getattr function takes two parameters, the name of the object and the name of the member data. This particular attribute works the same as we do use dot character.

What is __ DIR __ Python?

Python's __dir__() magic method implements the functionality of the dir() built-in function. Semantically, dir() returns all (function, object, or variable) names in a given scope. However, the magic method __dir__() converts any return value to a sorted list. Minimal Example.

How do I see all the attributes of an object in Python?

Use Python's vars() to Print an Object's Attributes The dir() function, as shown above, prints all of the attributes of a Python object.


2 Answers

Alex's answer was good, but providing you with a sample code since you asked for it :)

class foo:     def __init__(self):         self.a = "a"     def __getattr__(self, attribute):         return "You asked for %s, but I'm giving you default" % attribute   >>> bar = foo() >>> bar.a 'a' >>> bar.b "You asked for b, but I'm giving you default" >>> getattr(bar, "a") 'a' >>> getattr(bar, "b") "You asked for b, but I'm giving you default" 

So in short answer is

You use

__getattr__ to define how to handle attributes that are not found

and

getattr to get the attributes

like image 158
Kimvais Avatar answered Sep 20 '22 09:09

Kimvais


getattr is a built-in function taking (at least) two arguments: the object from which you're getting the attribute, and the string name of the attribute.

If the string name is a constant, say 'foo', getattr(obj, 'foo') is exactly the same thing as obj.foo.

So, the main use case for the built-in function getattr is when you don't have the attribute name as a constant, but rather as a variable. A second important use case is when you pass it three arguments, rather than just two: in that case, if the attribute is absent from the object, getattr returns the third, "default", argument, rather than raising an exception.

__getattr__ is a special method, defined in a class, that gets invoked when some attribute of an instance of that class is requested, and other normal ways to supply that attribute (via the instance's __dict__, slots, properties, and so on) all failed. You can define it, for example, when you want to delegate otherwise-undefined attribute lookups to other objects.

So your second example is wrong because the builtin getattr can never be called with a single argument.

The third one fails because the dictionary you're trying to "get an attribute" from does not have that attribute -- it has items, which are totally disjoint from attributes of course.

like image 32
Alex Martelli Avatar answered Sep 20 '22 09:09

Alex Martelli