我们如何确定属性属于实例还是属于类?

时间:2018-03-12 14:32:27

标签: python python-3.x class static-members member-variables

简介

在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))

1 个答案:

答案 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

讨论

  • 此生成器函数生成一个名称和属性列表,其中包含staticmethodclassmethod或类级变量。
  • 我还过滤掉了以dunder开头的名字(例如__doc__