打印所有类属性(不是实例属性)

时间:2018-02-24 13:03:31

标签: python-3.x class-attributes

我想打印所有类属性。不是实例属性。所以我希望得到['list1','list2']输出。

class MyClass():
    list1 = [1,2,3]
    list2 = ['a','b','c']
    def __init__(self, size, speed):
        self.size = size  
        self.speed = speed

我想获得['list1', 'list2']

1 个答案:

答案 0 :(得分:0)

attributes = [ attr for attr in list(vars(MyClass)) if attr[0] is not '_' and
             type(vars(MyClass)[attr]) is not type(lambda :0) ]

这输出以下内容:

print(attributes)
>>> ['list1', 'list2']

如果你班上有方法,"属性"不会包含您的方法'名称:

class MyClass():
        list1 = [1,2,3]
        list2 = ['a','b','c']
        def __init__(self, size, speed):
            self.size = size  
            self.speed = speed
        def energy(self, size, speed):
            return 0.5*size*speed**2

attributes = [ attr for attr in list(vars(MyClass)) if attr[0] is not '_' and
                 type(vars(MyClass)[attr]) is not type(lambda :0) ]

print(attributes)
>>>['list1', 'list2']