【问题标题】:How to execute function in parent class using 'exec' in child class?如何在子类中使用“exec”在父类中执行函数?
【发布时间】:2019-11-19 15:30:37
【问题描述】:

我想使用 execevalsuperclass 运行代码,但如何?
这是父类:

class A():
    def f1(self):
        print("hello")

这是子类:

class B(A):
    def __init__(self,func):
        self.funtion='super().'+func
        print(self.funtion)
        exec(self.funtion)

b=B('f1()')

结果

super().f1()
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-44-bdf8f567ee6e> in <module>
----> 1 b=B('f1()')

<ipython-input-43-3d6eddb1536b> in __init__(self, func)
      3         self.funtion='super().'+func
      4         print(self.funtion)
----> 5         exec(self.funtion)

<string> in <module>

RuntimeError: super(): no arguments

【问题讨论】:

  • 您是否有理由需要使用execeval
  • 我需要这样的课程。 python c = Condition(data=data,func='median',separate_negative = True) 和 func 在超类中定义。

标签: python exec eval


【解决方案1】:

只要方法在父类中定义(并且不被子类覆盖),就使用getattr

class A:
    def median(self):
        return ...

class Condition(A):
    def __init__(self, data, func, separate_negative):
        self.data = data
        self.func = getattr(self, func)
        self.separate_negative = separate_negative

然后要使用它,只需致电self.func()

【讨论】:

    【解决方案2】:

    您可以在getaddr() 中使用super() -

    class A():
        def f1(self):
            return "hello"
            #print("hello")
    
    class B(A):
        def __init__(self,func):
            self.function=getattr(super(), func)
            self.value = self.function()
            print(self.value)
    
    b=B('f1')
    

    效果很好。

    $./pysuperclass.py
    hello
    

    并确保您的f1() 返回而不是打印,打印不存储在变量中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2021-05-03
      • 2016-12-12
      • 2022-07-28
      • 2023-01-18
      • 2016-08-23
      相关资源
      最近更新 更多