Introduction and example of the built-in function getattr () in python, pythongetattr
In the official python documentation: getattr () is explained as follows:
getattr(object, name[, default])Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
Returns the object Value Based on the property name. If "name" is the name of the Object Property, the value of the corresponding property is returned.
'# -*- coding: utf-8 -*-'__author__ = 'lucas'class attrtest(object): def __init__(self): pass def trygetattr0(self): self.name = 'lucas' print self.name #equals to self.name print getattr(self,'name') def attribute1(self,para1): print 'attribute1 called and '+ para1+' is passed in as a parameter' def trygetattr(self): fun = getattr(self,'attribute1') print type(fun) fun('crown')if __name__=='__main__': test = attrtest() print 'getattr(self,\'name\') equals to self.name ' test.trygetattr0() print 'attribute1 is indirectly called by fun()' test.trygetattr() print 'attrribute1 is directly called' test.attribute1('tomato')
The result of executing this code is:
getattr(self,'name') equals to self.name lucaslucasattribute1 is indirectly called by fun()<type 'instancemethod'>attribute1 called and crown is passed in as a parameterattrribute1 is directly calledattribute1 called and tomato is passed in as a parameterProcess finished with exit code 0
The first function tryattribute0 () is very easy to understand, just as it is described in the definition. The second function tryattribute1 () is a bit confusing. In fact, the principle is not complex. We can see that the type of fun is instancemethod. Here you can think that for a function, the return value of getattr () is a pointer, And the pointer is assigned to the variable that accepts it, in the future, call is equivalent to calling the function pointed to by the variable.
Now that we know the principle, what is the role of getattr?
Are you familiar with reflection in java or c? One important function of reflection is delayed loading, which can be decoupled to make the system run more efficiently. As a dynamic language, python is obviously more powerful in this aspect,
Getattr () is a building block for implementing python reflection. Combined with other methods such as setattr () and dir (), we can do a lot of interesting things.
Let's look at the following scenarios:
1. I need to dynamically add methods in other classes in one class:
# If Class A has the following method: def addnewattributesfromotherclass (self, class_name): func_names = dir (class_name) for func_name in func_names: if not func_name.startswith ('_'): new_func = getattr (class_name, func_name) self. _ setattr _ (func_name, new_func ())
We only need:
a = A()b = B()a.addnewattributesfromotherclass(b)
In this way, a can call the 'non-private' method in B.
Help me explain the getattr built-in functions in Python
In fact, the main function of this method is to implement the reflection mechanism. That is to say, you can use strings to obtain the Method Instance. In this way, you can place the methods that a class may call in the configuration file and dynamically load them as needed.
_ Getattr _ in python
I hope you can use a simple example to help you with the python built-in method:
========== Test. py
Class a (object ):
Name = "Jim"
Def _ setattr _ (self, name, value ):
Self. _ dict _ [name] = value
Def _ getattr _ (self, name ):
Return name
B = ()
Print dir (B)
Print B. _ dict __
Print B. name
Print B. notexists
Print
B. name = "change"
Print dir (B)
Print B. _ dict __
Print B. name
Print B. notexists
============ Running result ==========
% Python test. py
['_ Class _', '_ delattr _', '_ dict _', '_ doc __', '_ getattr _', '_ getattribute _', '_ hash _', '_ init _', '_ module __', '_ new _', '_ reduce _', '_ performance_ex _', '_ repr _', '_ setattr __', '_ str _', '_ weakref _', 'name']
{}
Jim
Notexists
['_ Class _', '_ delattr _', '_ dict _', '_ doc __', '_ getattr _', '_ getattribute _', '_ hash _', '_ init _', '_ module __', '_ new _', '_ reduce _', '_ performance_ex _', '_ repr _', '_ setattr __', '_ str _', '_ weakref _', 'name']
{'Name': 'change '}
Change
Notexists
======================================
At the beginning, we can see that there was nothing empty in the _ dict _ object of B. When we used B. previously defined name attribute: "Jim"
When we use B. after name = "change", the built-in method _ setattr __is called by default. At this time, I did not directly operate on self. the name attribute is directly modified in self. _ dict _ ['name'] = 'change '. then I use B. obtained when the name is accessed ...... remaining full text>