luofeiyu_cu 发表于 2014-08-02 19:14

如何调用方法

>>> class test():
...   def fun1(self,x):
...         print(x+1)
...   def fun2(self,y):
...         print(y+2)
...   def callfun(fname,arg):
...         fname(arg)
...
>>> x=test()
>>> x.callfun(fun1,4)

需求:当我写x.callfun(fun1,4) 屏幕上输入5   ;x.callfun(fun2,4) 屏幕上输入6。   

ssfjhh 发表于 2014-08-02 19:41

回复 1# luofeiyu_cu


    为毛你总想写些稀奇古怪的代码?你先说说你为什么想这样实现?有什么需求导致你想这样实现?

icymirror 发表于 2014-08-02 23:31

回复 1# luofeiyu_cu
可以通过getattr来访问。
针对你的代码,可以修改为:class test():
    def fun1(self,x):
      print(x+1)
    def fun2(self,y):
      print(y+2)
    def callfun(self, fname,arg):
      getattr(self, fname)(arg)

item = test()
item.callfun("fun1", 4)
item.callfun("fun2", 9)

lizhihui_kevin 发表于 2014-09-17 17:13

:mrgreen: 回复 3# icymirror


   

murdercool 发表于 2014-09-18 09:58

class test():
    def fun1(self,x):
      print(x+1)
    def fun2(self,y):
      print(y+2)
    def callfun(self,fname,arg):
      getattr(self, fname)(arg)
x=test()
x.callfun('fun2',4)

blackold 发表于 2014-09-18 15:24

回复 2# ssfjhh

:mrgreen: :mrgreen:
   

bskay 发表于 2014-09-19 16:23

应该这样写:
x.callfun(x.fun1,4)
x.callfun(x.fun2,4)
页: [1]
查看完整版本: 如何调用方法