【问题标题】:Print all class attributes (not instance attributes)打印所有类属性(不是实例属性)
【发布时间】:2018-08-04 09:57:21
【问题描述】:

我想打印所有类属性。不是实例属性。所以我想得到['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']

【问题讨论】:

    标签: python-3.x class-attributes


    【解决方案1】:
    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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 2014-12-07
      • 1970-01-01
      • 2020-06-19
      • 2011-11-24
      • 2020-09-01
      相关资源
      最近更新 更多