简体   繁体   English

如何获取Python中给定类的成员列表?

[英]How do I get a list of members of a given class in Python?

Here what I want to get: 我想得到的是:

class Foo:

    def __init__(self, test1, test2, test3):
     self.test1=test1
     self.test2=test2
     self.test3=test3

Is there a way to get list of member variable names? 有没有一种方法来获取成员变量名称的列表?

Something similar like dir() function, but instead of this: 类似于dir()函数,但与此相反:

dir(Foo)
['__doc__', '__init__', '__module__']

You would have: 你将会拥有:

something(Foo)
['test1', 'test2', 'test3']

You're defining instance variables, not class variables. 您正在定义实例变量,而不是类变量。 To get instance variables, you'll have to instantiate it: 要获取实例变量,您必须实例化它:

>>> f = Foo(1, 2, 3)
>>> dir(f)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'test1', 'test2', 'test3']

There, you have all the attributes. 在那里,您具有所有属性。

But if you only want the attributes you declared, use f.__dict__ : 但是,如果只需要声明的属性,请使用f.__dict__

>>> f.__dict__
{'test3': 3, 'test2': 2, 'test1': 1}

Or alternatively, use vars(f) . 或者,使用vars(f)

But if you wanted to get the class variables, just refer to the class itself: 但是,如果要获取类变量,只需引用类本身即可:

>>> class Foo:
    abcd = 10
    def __init__(self, test1, test2, test3):
       self.test1=test1
       self.test2=test2
       self.test3=test3

>>> vars(Foo)
mappingproxy({'abcd': 10, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': None, '__module__': '__main__', '__init__': <function Foo.__init__ at 0x00000000032290D0>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>})
>>> dir(Foo)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'abcd']

Hope this helps! 希望这可以帮助!

General way to stores instances is using a class variable. 存储实例的一般方法是使用类变量。 But I'm not sure if this is what you want: 但是我不确定这是否是您想要的:

class Foo:
    names = {}

    def __init__(self, name):
        self.name = name
        Foo.names[name] = self

f1, f2, f3 = Foo('name1'), Foo('name2'), Foo('name3')
print Foo.names

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM