【问题标题】:Polymorphism when calling a static method from a static method in python从python中的静态方法调用静态方法时的多态性
【发布时间】:2019-06-02 22:46:38
【问题描述】:

我目前正在解决许多类将基于基类的问题。我希望这些类从基类继承一个静态函数,该基类又调用一个静态函数。但是,将为每个类定义第二个静态函数。

一个简单的例子是:

class foo():
   @staticmethod
   def fn1(x):
      return x

   @staticmethod
   def fn2(x, y):
      return foo.fn1(x + y)

class bar(foo):
   @staticmethod
   def fn1(x):
      return 2*x

使用上面的代码bar.fn2(1, 2) 返回foo.fn1(1 + 2) 而我希望它返回bar.fn1(1 + 2)

这是否可以在不为每个类定义 fn2 的情况下使用 python 中的静态方法?

感谢您的帮助!

【问题讨论】:

    标签: python oop inheritance static-methods


    【解决方案1】:

    fn2 改为类方法,以便它可以访问用于调用该方法的类:

    @classmethod
    def fn2(cls, x, y):
       return cls.fn1(x + y)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      相关资源
      最近更新 更多