Python-从父类到子类共享类输入

时间:2018-11-26 18:55:36

标签: python class

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

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)

1 个答案:

答案 0 :(得分:1)

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

如果只希望它始终绘图...只需在父级中调用绘图...

如果不传递任何参数,则希望将其默认设置为1,则在父构造函数中将plot=0更改为plot=1