如何在类中通过函数名称调用函数

王东东

如何在函数 C 中调用函数 B,仅通过其名称 == str(B) 而不使用 self.B()?

class A:
    def B(self):
        print('sth')
    def C(self):
        # I want to call function self.B() in here by its name which is str(B)

我想这样做的原因是:

class A:
    def C(self, person):
        if person == "John":
           self.John()
        elif person == "Ben":
           self.Ben()
    def John(self):
        print("I am john")
    def Ben(self):
        print("I am Ben")
A("John").C()

因为person变量必须是字符串,所以我想运行参数对应的函数:person,如果可以通过某种方式调用函数名,就不需要在def中添加额外的if和elif条件了C。

存入

正如对原始问题的评论中已经指出的那样,您需要访问实例上的方法。例如:

class A:
    def C(self, person):
        try:
            getattr(self, person)()
        except AttributeError:
            print(f'there is no method for `{person}` in the A class')
        
    def John(self):
        print("I am john")
        
    def Ben(self):
        print("I am Ben")
        
A().C('John')
I am john

A().C('Daniel')
there is no method for `Daniel` in the A class

尽管想知道为什么要实现这样的编程模式是合法的,getattr但是否正是出于类似的目的。不过,我同意没有更好解释的评论,这是一种应该避免的编程模式。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章