简介
在Python中,我希望获得属于该类的对象的所有属性的列表,而不是实例(所有静态属性的列表)。
测试潜在解决方案的一些代码:
class Klass:
static_var = 'static_var string'
def __init__(self):
self.instance_var = 'instance_var string'
def instance_method(self, *args, **kwargs):
pass
@staticmethod
def static_method(*args, **kwargs):
# can be passed almost anything and ignores it.
pass
obj = Klass()
尝试失败:
起初我尝试了以下内容:
def class_attrs_which_are_not_instance_attrs(obj):
return set(set(type(obj).__dict__) - set(obj.__dict__))
但是,obj.__dict__
为空,因此该函数仅返回type(obj).__dict__
我注意到的一些事情:
dir(type(obj))
== dir(obj)
type(obj).__dict__
⊆dir(type(obj))
答案 0 :(得分:1)
这是我的解决方案:
def static_attributes(obj):
"""
Generator to return a list of names and attributes which are
class-level variables or static methods
"""
klass = type(obj)
for name, attribute in klass.__dict__.items():
if not name.startswith('__') and \
(type(attribute) in {staticmethod, classmethod} or not callable(attribute)):
yield name, attribute
for name, attribute in static_attributes(obj):
print(name)
static_var
static_method
staticmethod
,classmethod
或类级变量。__doc__
)