python - 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)
解决方案
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=0
为plot=1
推荐阅读
- python - python类变量重置?
- qt - 如何在 QML javascript 功能块中创建 C++ QObject?
- google-cloud-platform - Google IAM 用于对最终用户进行身份验证?
- java - 枚举类方法给出空指针
- angular - Angular 6 业力测试中的“TypeError:expect(...).toBeVisible 不是函数”错误
- string - 如何在匹配模式之前和之后从文本文件中获取一串文本?
- lisp - Lisp - 如何进行随机排列
- c - C - 如何将 [600][400] 数组复制到 [4][4] 数组中,然后随机化元素位置?
- javascript - 无法让光标指针在悬停时显示
- scala - 数据节点的 minReplication 上的 Hadoop 远程异常错误