首页 > 解决方案 > Python - 从父类共享类输入到子类

问题描述

假设我有一个父类和多个子类:

class Parent(object):

    def _init__(self, generation):
        self.generation = generation

class Child1(Parent):

    def __init__(self, dimension, generation):
        super(Child1, self).__init__(generation)

        self.dimension = dimension
        print('child1')

class Child2(Parent):

    def __init__(self, dimension, generation):
        super(Child1, self).__init__(generation)

        self.dimension = dimension
        print('child2')

在我已经定义了所有子类之后,我意识到我想向__init__任何类添加一个命令。即,我希望他们执行plotting我定义的方法Parent

class Parent(object):

    def _init__(self, generation, plot = 0):
        self.generation = generation
        self.plot = plot
        if self.plot = 1: self.plotting


    def plotting(self):
        print('plotting here')

--

我怎样才能避免不得不为plot = 0每个子类提供论点?

基本上我现在只想打电话a = Child1(dimension, generation, plot = 1)

标签: pythonclass

解决方案


class Parent(object):

    def _init__(self, generation,plot=0):
        self.generation = generation
        if plot == 1:
           self.do_plot()

    def do_plot(self):
        print("You are doing something here i guess...")

然后在您的孩子初始化中,您只需传入情节...

class Child1(Parent):

    def __init__(self, dimension, generation,plot=1):
        super(Child1, self).__init__(generation,plot)
        self.dimension = dimension

您可以使用 kwargs 在未来进行更多扩展

class Parent(object):

    def _init__(self, generation,**kwargs):
        plot = kwargs.get("plot",0)
        self.generation = generation
        if plot == 1:
           self.do_plot()

    def do_plot(self):
        print("You are doing something here i guess...")

class Child1(Parent):

        def __init__(self, dimension, generation,**kwargs):
            super(Child1, self).__init__(generation,**kwargs)
            self.dimension = dimension

如果您只是希望它始终绘制...只需始终在父级中调用 plot...

如果您希望它默认为 1 如果没有传递任何内容,则在父构造函数中更改plot=0plot=1


推荐阅读