【问题标题】:Can python tell me which attributes of a class were defined in the current block?python 可以告诉我当前块中定义了类的哪些属性吗?
【发布时间】:2012-07-01 21:00:52
【问题描述】:

例如类声明:

class Something(Superclass):
    an_attribute = 1
    another_attribute = 'hello'

python有什么方法可以告诉我an_attributeanother_attribute是在这个类声明中定义的?

我猜这个问题的另一种表达方式是“我可以按声明它们的类过滤dir 结果吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    类的属性保存在它的特殊__dict__ 字段中。 __dict__ 仅包含为当前类定义的属性(以及特殊属性)。正如其他人提到的,它可以直接访问,也可以通过内置的vars() 函数访问。

    我强烈建议阅读this 文章,该文章解释了 Python 如何深入处理属性。

    【讨论】:

      【解决方案2】:

      Python 2.7

      class A:
          var1 = 2
          va2 = 2
      class B(A):
          var3 = 3
          var4 = 4
      
      print(A.__dict__.keys()) #prints ['va2', '__module__', 'var1', '__doc__']
      print(B.__dict__.keys()) #prints ['var4', '__module__', '__doc__', 'var3']
      

      Python 3:

      print(list(A.__dict__)) #prints ['__module__', 'var1', '__dict__', 'va2', '__weakref__', '__doc__']
      print(list(B.__dict__)) #prints ['var4', '__module__', '__doc__', 'var3']
      

      【讨论】:

      • @BasicWolf 每个帖子下方都有一个编辑按钮,SO 是一个协作网站,因此您可以使用它来编辑我的帖子,而不是投反对票。 :(
      • 有了这个推理,我们根本不需要反对按钮——我们可以总是修复错误。然而,由于风格偏好而投反对票是荒谬的。来自我的 +1。
      • 在 SO 有一个像样的代码编辑器之前,我们能否保存有关缩进级别的投诉。来自我的 +1
      • 伙计们,这是我的个人意见,但请查看 Ashwini Chaundhary 的其他答案@StackOverflow。 2个字符缩进。现在,考虑有一天你会阅读那种代码,并且没有花哨的 IDE 来重新缩进它。感觉舒服吗?这些标准,尤其是 PEP8 是为了我们每个人而创建的,它也是使 Python 代码可读的一部分。附言Ashwini Chaudhary,我看你还没有读过 PEP8,因为代码行超过 80 个字符 :)
      • 一个小的改进——在 Python 3 中打印一个键列表,而不是调用 keys(),你可以这样做:print(list(A.__dict__))
      【解决方案3】:

      SomeThing 类的属性字典可以通过vars(SomeThing) 访问。另请参阅documentation of vars()

      【讨论】:

        【解决方案4】:
        >>> class Something(list):
        ...     an_attribute = 1
        ...     another_attribute = 'hello'
        ... 
        >>> print vars(Something) == Something.__dict__
        True
        >>> 
        >>> print vars(Something)
        {'__module__': '__main__', '__doc__': None, 'an_attribute': 1, '__dict__': <attribute '__dict__' of 'Something' objects>, '__weakref__': <attribute '__weakref__' of 'Something' objects>, 'another_attribute': 'hello'}
        >>> 
        

        【讨论】:

          【解决方案5】:

          另一种方法是使用introspection,使用@AshwiniChaudhary 的示例:

          import inspect
          
          class A:
              var1 = 2
              var2 = 2
          
          class B(A):
              var3 = 3
              var4 = 4
          
          [member for member in inspect.getmembers(B) if member not in inspect.getmembers(A)]
          #prints [('var3', 3), ('var4', 4)]
          

          通过这种方法,您可以决定要从继承层次结构中的哪个类中“减去”成员,例如:

          class One:
              #members
          
          class Two:
              #members
          
          ...
          
          class N:
              #members
          
          [member for member in inspect.getmembers(N) if member not in inspect.getmembers(NMinusK)]
          

          【讨论】:

            【解决方案6】:

            有内置的hasattr函数

            hasattr(object, name)
            

            如果字符串是对象属性之一的名称,则结果为 True,否则为 False。 (这是通过调用 getattr(object, name) 并查看它是否引发异常来实现的。)

            【讨论】:

            • 我根本不明白这是如何回答这个问题的。具体来说,给定一个类Foo 及其子类Bar,无论属性是在Foo 还是Bar 中定义的,hasattr(Bar, attr) 都将返回true。
            猜你喜欢
            • 2010-10-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-02-14
            相关资源
            最近更新 更多