获取没有特殊属性的类对象 __dict__
-
20-09-2019 - |
题
为了获取所有定义的类属性,我尝试使用
TheClass.__dict__
但这也给了我特殊的属性。有没有办法只获取自定义属性,或者我必须自己“清理”字典?
解决方案
另一个解决方案:
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
您可以依靠命名约定的:
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__
。
我不认为有什么简单的,为什么会有?有魔术和用户定义的属性之间没有语言强制差。
如果你有一个用户定义的属性开始MYYN的解决方案将无法正常工作“__”。但是,它确实表明基于约定的解决办法:如果你要反思自己的类,你可以定义自己的命名约定,并就筛选
或许,如果你解释的需要,我们可以找到一个更好的解决方案。
不隶属于 StackOverflow