繁体   English   中英

从对象内的字符串名称调用函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM