繁体   English   中英

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

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

我想得到的是:

class Foo:

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

有没有一种方法来获取成员变量名称的列表?

类似于dir()函数,但与此相反:

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

你将会拥有:

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

您正在定义实例变量,而不是类变量。 要获取实例变量,您必须实例化它:

>>> 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']

在那里,您具有所有属性。

但是,如果只需要声明的属性,请使用f.__dict__

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

或者,使用vars(f)

但是,如果要获取类变量,只需引用类本身即可:

>>> 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']

希望这可以帮助!

存储实例的一般方法是使用类变量。 但是我不确定这是否是您想要的:

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