【发布时间】:2010-12-27 17:52:51
【问题描述】:
为了获取我尝试使用的所有已定义的类属性
TheClass.__dict__
但这也给了我特殊的属性。有没有办法只获取自定义属性,还是我必须自己“清理”字典?
【问题讨论】:
标签: python oop new-style-class
为了获取我尝试使用的所有已定义的类属性
TheClass.__dict__
但这也给了我特殊的属性。有没有办法只获取自定义属性,还是我必须自己“清理”字典?
【问题讨论】:
标签: python oop new-style-class
另一种解决方案:
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中定义)。【讨论】:
你无法清理__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']
这可能不可靠,因为您当然可以在课堂上覆盖或实现special/magic methods,如__item__ 或__len__。
【讨论】:
我不认为有什么简单的,为什么会有?魔法属性和用户定义属性之间没有语言强制的区别。
如果您有一个以“__”开头的用户定义属性,MYYN 的解决方案将不起作用。但是,它确实建议了一个基于约定的解决方案:如果您想内省自己的类,您可以定义自己的命名约定,并对其进行过滤。
也许如果您解释需要我们可以找到更好的解决方案。
【讨论】: