这是我想要得到的:
class Foo:
def __init__(self, test1, test2, test3):
self.test1=test1
self.test2=test2
self.test3=test3
Run Code Online (Sandbox Code Playgroud)
有没有办法获取成员变量名称列表?
类似于 dir() 函数的东西,但不是这样的:
dir(Foo)
['__doc__', '__init__', '__module__']
Run Code Online (Sandbox Code Playgroud)
你将会拥有:
something(Foo)
['test1', 'test2', 'test3']
Run Code Online (Sandbox Code Playgroud)
您正在定义实例变量,而不是类变量。要获取实例变量,您必须实例化它:
>>> 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']
Run Code Online (Sandbox Code Playgroud)
在那里,你拥有所有的属性。
但如果您只想要您声明的属性,请使用f.__dict__:
>>> f.__dict__
{'test3': 3, 'test2': 2, 'test1': 1}
Run Code Online (Sandbox Code Playgroud)
或者,使用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']
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
1785 次 |
| 最近记录: |