我正在尝试使用getattr(...). 下面的片段:
class cl1(module):
I =1
Name= 'name'+str(I)
Func= 'func'+str(I)
Namecall = gettattr(self,name)
Namecall = getattr(self,name)()
Run Code Online (Sandbox Code Playgroud)
这是获得以下代码的时候: self.name1 = self.func1()
希望循环多个这些,但代码不起作用。你能给些建议么?
首先,请对类使用大写字母,对变量使用小写字母,因为其他 Python 程序员更容易阅读:)
现在,您不需要在类本身中使用 getattr() 只需执行以下操作:
self.attribute
Run Code Online (Sandbox Code Playgroud)
但是,一个例子是:
class Foo(object): # Class Foo inherits from 'object'
def __init__(self, a, b): # This is the initialize function. Add all arguments here
self.a = a # Setting attributes
self.b = b
def func(self):
print('Hello World!' + str(self.a) + str(self.b))
>>> new_object = Foo(a=1, b=2) # Creating a new 'Foo' object called 'new_object'
>>> getattr(new_object, 'a') # Getting the 'a' attribute from 'new_object'
1
Run Code Online (Sandbox Code Playgroud)
但是,更简单的方法是直接引用属性
>>> new_object.a
1
>>> new_object.func()
Hello World!12
Run Code Online (Sandbox Code Playgroud)
或者,通过使用 getattr():
>>> getattr(new_object, 'func')()
Hello World!12
Run Code Online (Sandbox Code Playgroud)
虽然我解释了 getattr() 函数,但我似乎不明白您想要实现什么,请发布示例输出。