Ing*_*her 2 python introspection
说我有这个班:
class MyClass(object):
my_attrib = 'foo'
my_other_attrib = 'bar'
def mymethod():
pass
Run Code Online (Sandbox Code Playgroud)
现在我怎样才能获得类MyClass,WITHOUT方法和内置类等的属性__dict__?
当我{'my_attrib':'foo', 'my_other_attrib':'bar'}应用于上面的类时,我希望得到一本字典.
您可以过滤掉您不需要的所有内容__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}
Run Code Online (Sandbox Code Playgroud)
编辑:对于类属性和描述符,行为略有不同的替代方法:
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
Run Code Online (Sandbox Code Playgroud)
(实际上,这应该与第一个版本很少不同.)