[英]How can a subclass be created from a string passed to the superclass in python?
[英]Python & Classes - Can I use a method in a superclass that is going to be created in a subclass?
希望你们一切都好。 我需要做一些家庭作业,我提出了一个疑问,我不知道是否可以通过这种方式解决。 如果你能帮助我,你介意吗? 不管怎么说,还是要谢谢你。
假设我们有这个:
class human:
def dress(self, weather):
return color(weather)
class girl(human):
def color(self, weather):
if weather == 'rainy':
print('red')
else:
print('blue')
我可以这样做吗? 因为乍一看,我有一个问题,即人类的 color() 是未定义的(逻辑上)。 你可能会问,你为什么会这样想? 因为是解决问题的说明。 哪个最好解决呢?
再次感谢!
是的,你可以这么做。 在超类中拥有由子类定义的方法并不少见。 通常,超类将有一个占位符实现,该实现会引发一个异常,指示子类需要定义它——但这并不是工作所必需的。
class human:
def dress(self, weather):
return self.color(weather)
def color(self, weather):
raise NotImplementedError("Subclass needs to define this.")
class girl(human):
def color(self, weather):
if weather == 'rainy':
c = 'red'
else:
c = 'blue'
print(c)
return c
某些基类不打算直接使用,需要子类实现基 class 调用的方法。 如果您将此类 class 子类化并填写所需方法的实现.. 基础 class 已经定义的调用它们的方法将起作用。
例如,假设我们有一个女孩实例。 我们希望它适合天气。 即使子类没有定义dress()
,它仍然有那个方法,因为它继承了它。
>>> mary = girl()
>>>
>>> mary.dress("rainy")
red
在运行时,解释器运行dress()
的代码并在其中看到color()
。 然后它在girl
身上寻找 function 并找到它。 基础 class 是否定义它并不重要。
不,除非方法具有相同的名称,否则您不能从父 class 调用子 class 方法。 如果您也在父 class 中创建相同的方法“颜色”,则可以做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.