【问题标题】:What is getattr() exactly and how do I use it?究竟什么是 getattr() 以及如何使用它?
【发布时间】:2011-05-03 18:37:57
【问题描述】:

我最近read about the getattr() function。问题是我仍然无法掌握它的用法。我对getattr() 唯一了解的是getattr(li, "pop") 与调用li.pop 相同。

我不明白这本书何时提到你如何使用它来获取对函数的引用,而直到运行时才知道它的名称。一般来说,这可能是我在编程方面的菜鸟。任何人都可以对这个主题有所了解吗?我何时以及如何准确地使用它?

【问题讨论】:

  • 您在哪个部分遇到了问题?属性作为字符串?一流的功能?
  • 我认为我的问题是理解 getattr() 的概念。我还是不明白它的目的。
  • @Terence 我的回答不是让事情更清楚吗?
  • @Alois,你的回答确实消除了我的一些疑虑,但我仍然无法完全理解 getattr() 的用途。
  • @S.Lott,我做到了。文档只有定义,所以我对它的用法有点困惑。不过,在阅读了有关 getattr 的更多信息后,我现在了解它。

标签: python getattr


【解决方案1】:

Python 中的对象可以具有属性——数据属性和与这些(方法)一起工作的函数。实际上,每个对象都有内置属性(在 Python 控制台中尝试dir(None)dir(True)dir(...)dir(dir))。

例如,您有一个对象person,它有几个属性:namegender 等。

您访问这些属性(无论是方法还是数据对象)通常写成:person.nameperson.genderperson.the_method() 等。

但是,如果您在编写程序时不知道属性的名称怎么办?例如,您将属性名称存储在名为 attr_name 的变量中。

如果

attr_name = 'gender'

然后,而不是写

gender = person.gender

你可以写

gender = getattr(person, attr_name)

一些练习:

Python 3.4.0 (default, Apr 11 2014, 13:05:11)

>>> class Person():
...     name = 'Victor'
...     def say(self, what):
...         print(self.name, what)
... 
>>> getattr(Person, 'name')
'Victor'
>>> attr_name = 'name'
>>> person = Person()
>>> getattr(person, attr_name)
'Victor'
>>> getattr(person, 'say')('Hello')
Victor Hello

如果对象中不存在具有给定名称的属性,getattr 将引发 AttributeError

>>> getattr(person, 'age')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute 'age'

但是你可以传递一个默认值作为第三个参数,如果该属性不存在,则会返回:

>>> getattr(person, 'age', 0)
0

您可以使用getattrdir 来遍历所有属性名称并获取它们的值:

>>> dir(1000)
['__abs__', '__add__', ..., '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

>>> obj = 1000
>>> for attr_name in dir(obj):
...     attr_value = getattr(obj, attr_name)
...     print(attr_name, attr_value, callable(attr_value))
... 
__abs__ <method-wrapper '__abs__' of int object at 0x7f4e927c2f90> True
...
bit_length <built-in method bit_length of int object at 0x7f4e927c2f90> True
...

>>> getattr(1000, 'bit_length')()
10

此方法的实际用途是查找名称以testcall them 开头的所有方法。

getattr 类似,setattr 允许您设置具有其名称的对象的属性:

>>> setattr(person, 'name', 'Andrew')
>>> person.name  # accessing instance attribute
'Andrew'
>>> Person.name  # accessing class attribute
'Victor'
>>>

【讨论】:

  • 所以在我看来getattr(..)应该用在两种情况下:1.当属性名称是变量内部的值时(例如getattr(person, some_attr))和2.当我们需要使用第三个位置参数作为默认值(例如getattr(person, 'age', 24))。如果我看到像getattr(person, 'age') 这样的场景,在我看来它与person.age 相同,这让我认为person.age 更像Pythonic。对吗?
  • “可读性很重要”。当然person.agegetattr(person, "age") 好。当变量中有属性名称时,我使用getattr 是有意义的。
【解决方案2】:

getattr(object, 'x') object.x 完全等效

只有两种情况getattr 有用。

  • 你不能写object.x,因为你事先不知道你想要哪个属性(它来自一个字符串)。对于元编程非常有用。
  • 您想提供一个默认值。如果没有yobject.y 将引发AttributeError。但是getattr(object, 'y', 5) 会返回5

【讨论】:

  • 我认为第二个要点与答案的开头陈述不一致是不是不正确?
  • @skoh:实际上,开场白提到getattr 有两个参数(等效),第二个项目符号提到getattr 有3 个参数。即使它是不一致的,我可能会离开它,强调更重要。
  • @UlfGjerdingen:想想 javascript。 o.x 等价于 o['x']。但是第二个表达式可以与任何可以在运行时决定的o[some_string] 一起使用(例如,根据用户输入或对象检查),而在第一个表达式中,x 是固定的。
  • 为了恢复死灵,另一个用例是标识符包含非法字符,如.-(我现在正在处理)。 getattr(obj, 'some.val') 可以在 obj.some.val 不可用的地方工作。
  • @JürgenK.: 当然,self 的行为与任何其他对象一样,唯一的区别是它是自动传递的
【解决方案3】:

对我来说,getattr 最容易这样解释:

它允许您根据字符串的内容调用方法,而不是输入方法名称。

例如,您不能这样做:

obj = MyObject()
for x in ['foo', 'bar']:
    obj.x()

因为 x 不是builtin 类型,而是str。但是,您可以这样做:

obj = MyObject()
for x in ['foo', 'bar']:
    getattr(obj, x)()

它允许您根据输入动态连接对象。我发现它在处理自定义对象和模块时很有用。

【讨论】:

  • 这是一个非常直接和准确的答案。
  • 什么是object.x
  • @develarist 提问者没有示例供我作为我的答案的基础,所以MyObjectobjx(分别为类定义、类实例和属性)只是示例/模型数据,您应该在其中填写您自己想要访问的类和属性。 foobarbaz 在 linux/unix/foss 文档中经常用作占位符。
  • operator.methodcaller( ) 的设计目的与本示例中的相同,调用使用字符串定义的方法。我更喜欢示例中的实现。
【解决方案4】:

getattr 的一个非常常见的用例是将数据映射到函数。

例如,在 Django 或 Pylons 等 Web 框架中,getattr 可以直接将 Web 请求的 URL 映射到将要处理它的函数。例如,如果您深入了解 Pylons 的路由,您会发现(至少在默认情况下)它会截断请求的 URL,例如:

http://www.example.com/customers/list

分为“客户”和“列表”。然后它搜索名为CustomerController 的控制器类。假设它找到了该类,它创建该类的一个实例,然后使用getattr 获取它的list 方法。然后它调用该方法,将请求作为参数传递给它。

一旦您掌握了这个想法,扩展 Web 应用程序的功能就变得非常容易:只需向控制器类添加新方法,然后在您的页面中创建使用这些方法的适当 URL 的链接。 getattr 让这一切成为可能。

【讨论】:

    【解决方案5】:

    这是一个快速而肮脏的示例,说明一个类如何根据使用 getattr() 在哪个操作系统上执行不同版本的保存方法来触发不同版本的保存方法。

    import os
    
    class Log(object):
        def __init__(self):
            self.os = os.name
        def __getattr__(self, name):
            """ look for a 'save' attribute, or just 
              return whatever attribute was specified """
            if name == 'save':
                try:
                    # try to dynamically return a save 
                    # method appropriate for the user's system
                    return getattr(self, self.os)
                except:
                    # bail and try to return 
                    # a default save method
                    return getattr(self, '_save')
            else:
                return getattr(self, name)
    
        # each of these methods could have save logic specific to 
        # the system on which the script is executed
        def posix(self): print 'saving on a posix machine'
        def nt(self): print 'saving on an nt machine'
        def os2(self): print 'saving on an os2 machine'
        def ce(self): print 'saving on a ce machine'
        def java(self): print 'saving on a java machine'
        def riscos(self): print 'saving on a riscos machine'
        def _save(self): print 'saving on an unknown operating system'
    
        def which_os(self): print os.name
    

    现在让我们在一个例子中使用这个类:

    logger = Log()
    
    # Now you can do one of two things:
    save_func = logger.save
    # and execute it, or pass it along 
    # somewhere else as 1st class:
    save_func()
    
    # or you can just call it directly:
    logger.save()
    
    # other attributes will hit the else 
    # statement and still work as expected
    logger.which_os()
    

    【讨论】:

      【解决方案6】:

      除了这里所有令人惊叹的答案之外,还有一种方法可以使用 getattr 来节省大量代码并使其保持舒适。这个想法是在有时可能是必需的代码的可怕表示之后产生的。

      场景

      假设你的目录结构如下:

      - superheroes.py
      - properties.py
      

      而且,您可以在superheroes.py 中获取有关ThorIron ManDoctor Strange 的信息。您非常巧妙地将properties.py 中所有这些属性的属性写在一个紧凑的dict 中,然后访问它们。

      properties.py

      thor = {
          'about': 'Asgardian god of thunder',
          'weapon': 'Mjolnir',
          'powers': ['invulnerability', 'keen senses', 'vortex breath'], # and many more
      }
      iron_man = {
          'about': 'A wealthy American business magnate, playboy, and ingenious scientist',
          'weapon': 'Armor',
          'powers': ['intellect', 'armor suit', 'interface with wireless connections', 'money'],
      }
      doctor_strange = {
          'about': ' primary protector of Earth against magical and mystical threats',
          'weapon': 'Magic',
          'powers': ['magic', 'intellect', 'martial arts'],
      }
      

      现在,假设您想在superheroes.py 中按需返回每个人的功能。所以,有像

      这样的功能
      from .properties import thor, iron_man, doctor_strange
      
      
      def get_thor_weapon():
          return thor['weapon']
      
      
      def get_iron_man_bio():
          return iron_man['about']
      
      
      def get_thor_powers():
          return thor['powers']
      

      ...以及更多基于键和超级英雄返回不同值的函数。

      getattr 的帮助下,您可以执行以下操作:

      from . import properties
      
      
      def get_superhero_weapon(hero):
          superhero = getattr(properties, hero)
          return superhero['weapon']
      
      
      def get_superhero_powers(hero):
          superhero = getattr(properties, hero)
          return superhero['powers']
      

      您大大减少了代码行数、函数和重复次数!

      当然,如果你有像 properties_of_thor 这样的坏名字,可以通过简单的操作来创建和访问它们

      def get_superhero_weapon(hero):
          superhero = 'properties_of_{}'.format(hero)
          all_properties = getattr(properties, superhero)
          return all_properties['weapon']
      

      注意:对于这个特殊问题,可以有更聪明的方法来处理这种情况,但我们的想法是提供有关在正确的地方使用 getattr 来编写更简洁的代码的见解。

      【讨论】:

        【解决方案7】:
        # getattr
        
        class hithere():
        
            def french(self):
                print 'bonjour'
        
            def english(self):
                print 'hello'
        
            def german(self):
                print 'hallo'
        
            def czech(self):
                print 'ahoj'
        
            def noidea(self):
                print 'unknown language'
        
        
        def dispatch(language):
            try:
                getattr(hithere(),language)()
            except:
                getattr(hithere(),'noidea')()
                # note, do better error handling than this
        
        dispatch('french')
        dispatch('english')
        dispatch('german')
        dispatch('czech')
        dispatch('spanish')
        

        【讨论】:

        • 您能否详细说明您的答案,添加更多关于您提供的解决方案的描述?
        【解决方案8】:

        我有时使用getattr(..) 在代码中使用它们之前延迟初始化次要属性。

        比较以下:

        class Graph(object):
            def __init__(self):
                self.n_calls_to_plot = 0
        
            #...
            #A lot of code here
            #...
        
            def plot(self):
                self.n_calls_to_plot += 1
        

        到这里:

        class Graph(object):
            def plot(self):
                self.n_calls_to_plot = 1 + getattr(self, "n_calls_to_plot", 0)
        

        第二种方式的好处是n_calls_to_plot只出现在代码中使用它的地方周围。这有利于可读性,因为 (1) 在阅读它的使用方式时,您可以立即看到它以什么值开头,(2) 它不会在 __init__(..) 方法中引入干扰,理想情况下应该是关于概念状态类,而不是某些实用程序计数器,由于技术原因(例如优化)仅由函数的方法之一使用,并且与对象的含义无关。

        【讨论】:

          【解决方案9】:

          当我从存储在类中的数据创建 XML 文件时,如果属性不存在或类型为 None,我经常会收到错误消息。在这种情况下,我的问题不是不知道属性名称是什么,如您的问题所述,而是数据是否曾经存储在该属性中。

          class Pet:
              def __init__(self):
                  self.hair = None
                  self.color = None
          

          如果我使用hasattr 执行此操作,即使属性值的类型为None,它也会返回True,这将导致我的ElementTree set 命令失败。

          hasattr(temp, 'hair')
          >>True
          

          如果属性值的类型为 Nonegetattr 也会返回它,这将导致我的 ElementTree set 命令失败。

          c = getattr(temp, 'hair')
          type(c)
          >> NoneType
          

          我现在使用以下方法来处理这些情况:

          def getRealAttr(class_obj, class_attr, default = ''):
              temp = getattr(class_obj, class_attr, default)
              if temp is None:
                  temp = default
              elif type(temp) != str:
                  temp = str(temp)
              return temp
          

          这是我使用getattr的时间和方式。

          【讨论】:

            【解决方案10】:

            在 Python 中实现 switch 语句时 getattr() 的另一种用法。它使用两种反射来获取案例类型。

            import sys
            
            class SwitchStatement(object):
                """ a class to implement switch statement and a way to show how to use gettattr in Pythion"""
            
                def case_1(self):
                    return "value for case_1"
            
                def case_2(self):
                    return "value for case_2"
            
                def case_3(self):
                    return "value for case_3"
            
                def case_4(self):
                    return "value for case_4"
            
                def case_value(self, case_type=1):
                    """This is the main dispatchmethod, that uses gettattr"""
                    case_method = 'case_' + str(case_type)
                    # fetch the relevant method name
                    # Get the method from 'self'. Default to a lambda.
                    method = getattr(self, case_method, lambda: "Invalid case type")
                    # Call the method as we return it
                    return method()
            
            def main(_):
                switch = SwitchStatement()
                print swtich.case_value(_)
            
            if __name__ == '__main__':
                main(int(sys.argv[1]))
            

            【讨论】:

            • 我喜欢这个答案,但请修正小错别字
            【解决方案11】:

            setattr()

            我们使用 setattr 来为我们的类实例添加一个属性。我们传递类实例、属性名称和值。

            getattr()

            通过 getattr 我们检索这些值

            例如

            Employee = type("Employee", (object,), dict())
            
            employee = Employee()
            
            # Set salary to 1000
            setattr(employee,"salary", 1000 )
            
            # Get the Salary
            value = getattr(employee, "salary")
            
            print(value)
            

            【讨论】:

              【解决方案12】:

              我认为这个例子是不言自明的。它运行第一个参数的方法,其名称在第二个参数中给出。

              class MyClass:
                 def __init__(self):
                    pass
                 def MyMethod(self):
                    print("Method ran")
              
              # Create an object
              object = MyClass()
              # Get all the methods of a class
              method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
              # You can use any of the methods in method_list
              # "MyMethod" is the one we want to use right now
              
              # This is the same as running "object.MyMethod()"
              getattr(object,'MyMethod')()
              

              【讨论】:

                【解决方案13】:

                https://www.programiz.com/python-programming/methods/built-in/getattr也澄清了

                class Person:
                    age = 23
                    name = "Adam"
                
                person = Person()
                print('The age is:', getattr(person, "age"))
                print('The age is:', person.age)
                

                年龄:23​​

                年龄:23​​

                class Person:
                    age = 23
                    name = "Adam"
                
                person = Person()
                
                # when default value is provided
                print('The sex is:', getattr(person, 'sex', 'Male'))
                
                # when no default value is provided
                print('The sex is:', getattr(person, 'sex'))
                

                性别是:男

                AttributeError: 'Person' 对象没有属性 'sex'

                【讨论】:

                  【解决方案14】:

                  我在Python2.7.17中试过

                  有些人已经回答了。但是我试图打电话 getattr(obj, 'set_value') 这并没有执行 set_value 方法,所以我改为 getattr(obj, 'set_value')() --> 这有助于调用相同的方法。

                  示例代码:

                  示例 1:

                      class GETATT_VERIFY():
                         name = "siva"
                         def __init__(self):
                             print "Ok"
                         def set_value(self):
                             self.value = "myself"
                             print "oooh"
                      obj = GETATT_VERIFY()
                      print getattr(GETATT_VERIFY, 'name')
                      getattr(obj, 'set_value')()
                      print obj.value
                  

                  【讨论】:

                    猜你喜欢
                    • 2021-11-12
                    • 2013-07-28
                    • 2017-02-14
                    • 1970-01-01
                    • 1970-01-01
                    • 2019-12-23
                    相关资源
                    最近更新 更多