获取没有特殊属性的类对象__dict__

时间:2009-12-17 16:58:39

标签: python oop new-style-class

为了获得所有已定义的类属性,我尝试使用

TheClass.__dict__

但这也给了我特殊的属性。有没有办法只获得自定义的属性,还是我必须自己“清理”这个词?

3 个答案:

答案 0 :(得分:4)

另一种解决方案:

class _BaseA(object):
    _intern = object.__dict__.keys()

class A(_BaseA):
    myattribute = 1

print filter(lambda x: x not in A._intern+['__module__'], A.__dict__.keys())

我认为这不是非常强大,可能还有更好的方法。

这确实解决了其他一些答案指出的一些基本问题:

  • 无需基于'name convention'过滤
  • 提供您自己的魔术方法实现,例如: __len__没问题(在A中定义)。

答案 1 :(得分:3)

您无法清除__dict__

AttributeError: attribute '__dict__' of 'type' objects is not writable

你可以依靠naming conventions

class A(object):
    def __init__(self, arg):
        self.arg = arg

    class_attribute = "01"    

print [ a for a in A.__dict__.keys() 
        if not (a.startswith('__') and a.endswith('__')) ]

# => ['class_attribute']

这可能不太可靠,因为您当然可以覆盖或实施类__item____len__中的special/magic methods

答案 2 :(得分:2)

我认为没有什么简单的,为什么会有?魔术和用户定义的属性之间没有语言强制区别。

如果您有一个以“__”开头的用户定义属性,MYYN的解决方案将无效。但是,它确实建议了一个基于约定的解决方案:如果你想内省你自己的类,你可以定义自己的命名约定,并对其进行过滤。

也许如果您解释需要我们可以找到更好的解决方案。

相关问题