looping over all member variables of a class in python
如何获得可迭代类中所有变量的列表?有点像locals(),但是对于一个类
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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) |
这个应该会回来
1 2 3 | >>> e = Example() >>> e.as_list() bool143, bool2, foo |
1 | dir(obj) |
提供对象的所有属性。您需要自己从方法等中筛选出成员:
1 2 3 4 5 6 7 8 9 10 | 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 |
会给你:
1 | ['blah', 'bool143', 'bool2', 'foo', 'foobar2000'] |
如果只需要变量(不带函数),请使用:
1 | vars(your_object) |
@Truppo:您的答案几乎是正确的,但是Callable总是返回false,因为您只是传入一个字符串。您需要如下内容:
1 | [attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")] |
过滤掉功能
1 2 3 4 5 6 | >>> 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'] |
—正如您所看到的,这为您提供了所有属性,因此您需要过滤掉一点。但基本上,你要找的是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 |
这样做的简单方法是将类的所有实例保存在
1 2 3 | a = Example() b = Example() all_examples = [ a, b ] |
物体不会自发地出现。程序的某些部分出于某种原因创建了它们。创建是有原因的。将它们收集到一个列表中也是有原因的。
如果你使用工厂,你可以这样做。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 |