[英]Calling function from string name within object
我有以下两节课:
class A(object):
def caller(self,name):
# want to invoke call() here when name="call"
class B(A):
def call(self):
print("hello")
给定以下内容:
x= B()
x.caller("call") # I want to have caller() invoke call() on the name.
我不想检查name
的值,我希望它自动将给定的字符串作为函数调用self。
使用__getattribute__
class A(object):
def caller(self,name):
self.__getattribute__(name)()
class B(A):
def call(self):
print("hello")
x= B()
x.caller("call")
产量
hello
也可以使用eval
class A(object):
def caller(self,name):
eval('self.%s()' % name)
class B(A):
def call(self):
print("hello")
x= B()
x.caller("call")
产量
你好[以0.6秒完成]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.