获取类的属性和对象属性(不包括方法和内置项)
假设我有这样一个类:
class MyClass(object):
my_attrib = 'foo'
my_other_attrib = 'bar'
def mymethod():
pass
现在我想要获取这个类 MyClass 的属性,想要的只是属性,不包括方法和像 __dict__
这样的内置内容,应该怎么做呢?
我希望得到一个字典,内容像 {'my_attrib':'foo', 'my_other_attrib':'bar'}
,应用到上面的类时能得到这样的结果。
4 个回答
2
__dict__
可以让你获取所有相关的信息,但你也可以考虑使用 C
扩展来实现你想要的功能。不过我不太明白为什么你会选择这样做。
你可以使用 types
(文档)来区分 __dict__
中的不同成员。
4
这段代码应该能让你接近想要的结果:
import inspect
class MyClass(object):
my_attrib = 'foo'
my_other_attrib = 'bar'
def mymethod():
pass
for name, value in inspect.getmembers(MyClass):
if not inspect.ismethod(value) and not name.startswith('__'):
print name
运行后会输出:
my_attrib
my_other_attrib
注意 - 可能还有更好或更官方的方法来实现这个,但这应该能给你一个正确的方向。
11
你可以从 __dict__
中筛选出你不需要的东西:
def getAttributes(clazz):
return {name: attr for name, attr in clazz.__dict__.items()
if not name.startswith("__")
and not callable(attr)
and not type(attr) is staticmethod}
编辑: 还有一种替代方法,它在处理类属性和描述符时表现得稍微不同:
def getAttributes2(clazz):
attrs = {}
for name in vars(clazz):
if name.startswith("__"):
continue
attr = getattr(clazz, name)
if callable(attr):
continue
attrs[name] = attr
return attrs
(实际上,这种情况和第一种方法几乎没有区别。)