在Python中对self使用getattr函数
我正在尝试通过一个循环来调用多个函数,使用的是 getattr(...)
。下面是我的代码片段:
class cl1(module):
I =1
Name= 'name'+str(I)
Func= 'func'+str(I)
Namecall = gettattr(self,name)
Namecall = getattr(self,name)()
这段代码的意思是:self.name1 = self.func1()
我希望能循环调用多个这样的代码,但现在代码不太好使。你能给点建议吗?
1 个回答
6
首先,类的名字要用大写字母,而变量的名字要用小写字母,这样其他Python程序员看起来会更容易理解 :)
接下来,你在类里面其实不需要使用getattr()这个函数。你可以直接这样做:
self.attribute
不过,给你一个例子:
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
其实,更简单的方法就是直接引用属性。
>>> new_object.a
1
>>> new_object.func()
Hello World!12
或者,你也可以使用getattr():
>>> getattr(new_object, 'func')()
Hello World!12
虽然我解释了getattr()这个函数,但我似乎不太明白你想要达到什么效果,可以发个示例输出吗?