对于这种情况,您可以dir
在对象上使用,并且只获取不以 ie 开头的属性,__
即忽略魔术方法:
In [496]: class Foo():
...: def __init__(self):
...: self.max_count = 2
...: @property
...: def get_max_plus_one(self):
...: return self.max_count + 1
...:
In [497]: f = Foo()
In [498]: {prop: getattr(f, prop) for prop in dir(f) if not prop.startswith('__')}
Out[498]: {'get_max_plus_one': 3, 'max_count': 2}
要处理不以 开头的常规方法__
,您可以添加一个callable
测试:
In [521]: class Foo():
...: def __init__(self):
...: self.max_count = 2
...: @property
...: def get_max_plus_one(self):
...: return self.max_count + 1
...: def spam(self):
...: return 10
...:
In [522]: f = Foo()
In [523]: {prop: getattr(f, prop) for prop in dir(f) if not (prop.startswith('__') or callable(getattr(Foo, prop, None)))}
Out[523]: {'get_max_plus_one': 3, 'max_count': 2}