1

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

TheClass.__dict__

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

4

3 回答 3

5

另一种解决方案:

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 中定义)。
于 2009-12-17T18:58:48.370 回答
3

您无法清洁__dict__

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

您可以依赖命名约定

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__在您的课程中。

于 2009-12-17T17:09:15.870 回答
2

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

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

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

于 2009-12-17T17:14:57.107 回答