Introduction to the built-in functions getattr () in Python and examples

Source: Internet
Author: User

In the official Python document: GetAttr () is interpreted as follows:

?
123 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 an object value based on the property name. If "name" is the name of the object property, the value of the corresponding property is returned.

?
12345678910111213141516171819202122232425262728293031 ‘# -*- 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 this code execution is:

?
12345678910 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 well understood, as the definition says. The second function, Tryattribute1 (), is a bit confusing. In fact, the principle is not complicated, we see the fun type is Instancemethod, here you can think: for the function, the return value of GetAttr () is a pointer, the pointer is assigned to the variable to accept it, and then call this variable is equal to the function that calls the variable point.

Principle we know, what is the role of the getattr?

Are you familiar with the reflection in Java or C #? One of the important functions of reflection is to delay loading so that it can be decoupled, which makes the system more efficient to run. As a dynamic language, Python is clearly more powerful in this area,

GetAttr () is a block that implements Python reflection, and in combination with other methods such as SetAttr (), dir (), we can make a lot of interesting things.

Let's look at the following scenario:

1. I need to dynamically add methods from other classes in one class:

?
1234567 #如果类A中有如下方法: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:

?
12345 a =A() b = B()a.addnewattributesfromotherclass(b)

So that a can invoke the ' non-private ' method in B.

Introduction to the built-in functions getattr () in Python and examples

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.