【问题标题】:looping over all member variables of a class in python在python中循环一个类的​​所有成员变量
【发布时间】:2010-11-26 17:58:40
【问题描述】:

如何获得可迭代类中所有变量的列表?有点像 locals(),但是对于一个类

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

    def as_list(self)
       ret = []
       for field in XXX:
           if getattr(self, field):
               ret.append(field)
       return ",".join(ret)

这应该返回

>>> e = Example()
>>> e.as_list()
bool143, bool2, foo

【问题讨论】:

标签: python


【解决方案1】:
dir(obj)

为您提供对象的所有属性。 您需要自己从方法等中过滤掉成员:

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

example = Example()
members = [attr for attr in dir(example) if not callable(getattr(example, attr)) and not attr.startswith("__")]
print members   

会给你:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']

【讨论】:

  • 为什么要实例化一个对象:dir(Example()) 而不仅仅是类类型 dir(Example)
  • 你如何获得这些值?
  • @knutole: getattr(object, attr)
  • callable(attr) 是如何工作的? attr 不是字符串吗?
  • 如果你想检查它是否可调用,你应该使用vars(Example).items()vars(instance.__class__).items() 而不是dir(),因为dir 只会返回'strings 作为名称..跨度>
【解决方案2】:

如果您只想要变量(没有函数),请使用:

vars(your_object)

【讨论】:

  • 您仍然需要过滤 vars 但这是正确答案
  • 真的很喜欢这种方法,例如,在通过网络发送状态之前,它会使用它来找出要序列化的内容...
  • vars包含类变量,只包含实例变量。
  • @DilithiumMatrix 您需要在类本身上使用 vars(THECLASSITSELF) 来获取类变量。在下面检查我的答案。
  • 使用此方法专门回答OP的问题:members = list(vars(example).keys()) as(至少在python3中)vars返回一个dict,将成员变量的名称映射到它的值。
【解决方案3】:

@truppo:您的答案几乎是正确的,但 callable 将始终返回 false,因为您只是传入一个字符串。您需要以下内容:

[attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")]

过滤掉函数

【讨论】:

  • ClassName.__dict__["__doc__"] 这将过滤掉函数、内置变量等,并为您提供所需的字段!
【解决方案4】:
>>> a = Example()
>>> dir(a)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__',
'__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'bool143', 'bool2', 'blah',
'foo', 'foobar2000', 'as_list']

— 如您所见,它为您提供了 所有 属性,因此您必须过滤掉一点。但基本上,dir() 就是您要找的。​​p>

【讨论】:

  • ClassName.__dict__["__doc__"] 这将过滤掉函数、内置变量等,并为您提供所需的字段!
【解决方案5】:

类似于vars(),可以使用以下代码列出所有类属性。相当于vars(example).keys()

example.__dict__.keys()

【讨论】:

  • ClassName.__dict__["__doc__"] 这将过滤掉函数、内置变量等,并为您提供所需的字段!
【解决方案6】:
ClassName.__dict__["__doc__"]

这将过滤掉函数、内置变量等,并为您提供所需的字段!

【讨论】:

    【解决方案7】:
    row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns} if r else {}
    

    使用这个。

    【讨论】:

    • 误导。默认情况下,类中没有属性“table”。
    • ClassName.__dict__["__doc__"] 这将过滤掉函数、内置变量等,并为您提供所需的字段!
    【解决方案8】:
        class Employee:
        '''
        This class creates class employee with three attributes 
        and one function or method
        '''
    
        def __init__(self, first, last, salary):
            self.first = first
            self.last = last
            self.salary = salary
    
        def fullname(self):
            fullname=self.first + ' ' + self.last
            return fullname
    
    emp1 = Employee('Abhijeet', 'Pandey', 20000)
    emp2 = Employee('John', 'Smith', 50000)
    
    print('To get attributes of an instance', set(dir(emp1))-set(dir(Employee))) # you can now loop over
    

    【讨论】:

    • ClassName.__dict__["__doc__"] 这将过滤掉函数、内置变量等,并为您提供所需的字段!
    【解决方案9】:

    执行此操作的简单方法是将类的所有实例保存在 list 中。

    a = Example()
    b = Example()
    all_examples = [ a, b ]
    

    对象不会自发地出现。您的程序的某些部分创建它们是有原因的。创作是有原因的。将它们收集到一个列表中也是有原因的。

    如果你使用工厂,你可以这样做。

    class ExampleFactory( object ):
        def __init__( self ):
            self.all_examples= []
        def __call__( self, *args, **kw ):
            e = Example( *args, **kw )
            self.all_examples.append( e )
            return e
        def all( self ):
            return all_examples
    
    makeExample= ExampleFactory()
    a = makeExample()
    b = makeExample()
    for i in makeExample.all():
        print i
    

    【讨论】:

    • 我喜欢这个想法(我实际上可能会在当前项目中使用它)。但是,这不是问题的答案:OP 想要列出属性,而不是实例本身。
    • @balpha:哎呀。没读过问题。 90% 的时间,它是“我如何找到一个类的所有实例”的副本。实际问题(现在您指出了)是不明智的。你知道实例变量,列个清单就行了。
    • ClassName.__dict__["__doc__"] 这将过滤掉函数、内置变量等,并为您提供所需的字段!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多