[英]Pass method to function using method name from string variable
I have a class with a constructor, two other methods, and a member list with the names of the two methods.我有一个带有构造函数的类、两个其他方法和一个包含这两个方法名称的成员列表。
class Foo():
def __init__(self):
self.methods = ["self.foo", "self.bar"]
def foo(self):
print("foo")
return 0
def bar(self):
print("bar")
return 0
I have a function that takes a function as an argument, like this.我有一个将函数作为参数的函数,就像这样。
myFunction(func)
The function has global scope and would be used like this.该函数具有全局作用域,可以像这样使用。
myFunction(self.foo)
I want to iterate through the items in the self.methods list and make a call to the function for each method name, but, as expected, a string is passed rather than the method itself.我想遍历 self.methods 列表中的项目并为每个方法名称调用该函数,但是,正如预期的那样,传递的是一个字符串而不是方法本身。 How do I pass the method like the above example, so like self.foo
not "self.foo"
?我如何像上面的例子一样传递方法,比如self.foo
而不是"self.foo"
?
From what I understand you can try this.据我了解,你可以试试这个。
class Foo():
def __init__(self):
self.method=['foo','bar']
def foo(self):
print('foo')
def bar(self):
print('bar')
def run_all(self):
for m in self.method:
getattr(self,m)()
a=Foo()
a.run_all() # iterating through self.method and executing them
# foo
# bar
You want somwthing like this?你想要这样的东西吗?
class Foo():
def __init__(self):
self.methods = [self.foo(), self.bar()]
def foo(self):
print("foo")
return 0
def bar(self):
print("bar")
return 0
foo_obj = Foo()
What about:关于什么:
class Foo():
def __init__(self):
self.methods = self.foo, self.bar
def run_methods(self):
for method in self.methods:
print('Running method {}'.format(method.__name__))
method()
def foo(self):
print("foo")
return 0
def bar(self):
print("bar")
return 0
So, you can run your methods by calling run_methods
.因此,您可以通过调用run_methods
来运行您的方法。 If you want to access their names as well, you can always do that via their respective __name__
methods, as above.如果你也想访问他们的名字,你总是可以通过他们各自的__name__
方法来做到这__name__
,如上所述。
f = Foo()
f.run_methods()
# Output:
#
# Running method foo
# foo
# Running method bar
# bar
EDIT: As another person suggested, you should edit your question to describe in more detail what myFunction(fun) does.编辑:正如另一个人建议的那样,您应该编辑您的问题以更详细地描述 myFunction(fun) 的作用。 But inded, you should probably use a different approach than passing the actual names as strings.但是实际上,您可能应该使用与将实际名称作为字符串传递不同的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.