将现有函数添加到子类

时间:2017-11-23 12:41:48

标签: python subclass

我正在制作一些需要实现run方法的子类。他们都遵循一种模式:

from mylib import transformation_function_1
from mylib import transformation_function_2

def SubClass1(ParentClass):
    def run(self):
        subclass_data = transformation_function_1(self.parent_data)
        # Some other fixed logic.

def SubClass2(ParentClass):
    def run(self):
        subclass_data = transformation_function_2(self.parent_data)
        # Some other fixed logic.

无论如何我可以在中级课程中提出这个逻辑吗?像这样的东西?

from mylib import transformation_function_1
from mylib import transformation_function_2

def TransformationBase(ParentClass):

    @abstractclassmethod
    def transformation_function():
        raise NotImplementedError

    def run(self):
        subclass_data = transformation_function(self.parent_data)
        # Some other fixed logic.

def SubClass1(TransformationBase):
    transformation_function = transformation_function_1

def SubClass2(TransformationBase):
    transformation_function = transformation_function_2

谢谢!

2 个答案:

答案 0 :(得分:1)

特殊函数staticmethod允许将本地方法声明为静态方法。假设您想要声明类并且希望子类使用外部自由函数,您可以这样做:

>>> class TransformationBase:

    def transformation_function():
        raise NotImplementedError

    def run(self):
        subclass_data = self.transformation_function(self.parent_data)
        # Some other fixed logic.


>>> def transformation_function_1(data):
    print('F1', data)


>>> def transformation_function_2(data):
    print('F2', data)
    return 2

>>> class SubClass1(TransformationBase):
    transformation_function = staticmethod(transformation_function_1)
    parent_data = "P1"


>>> c1 = SubClass1()
>>> c1.run()
F1 P1
>>> 

答案 1 :(得分:0)

您可以执行以下操作:

class SubClass(TransformationBase):
  def transformation_function(*args, **kwargs):
    return transformation_function1(*args, **kwargs)