我的问题解释起来有点棘手。让我举个例子。我有以下类定义:
class Person(object):
def __init__(self, name):
self.name = name
def say(self, stuff):
return self.name + ' says: ' + stuff
def __str__(self):
return self.name
class Lecturer(Person):
def lecture(self, stuff):
return 'I believe that ' + Person.say(self, stuff)
class Professor(Lecturer):
def say(self, stuff):
return self.name + ' says: ' + self.lecture(stuff)
class ArrogantProfessor(Professor):
def say(self, stuff):
return self.name + ' says: It is obvious that ' + Lecturer.lecture(self, stuff)
def lecture(self, stuff):
return 'It is obvious that ' + Lecturer.lecture(self, stuff)
现在我想修改除ArrogantProfessor
类之外的任何类,以便我得到以下内容:
>>> pe.say('the sky is blue')
Prof. eric says: I believe that eric says: the sky is blue
>>> ae.say('the sky is blue')
Prof. eric says: It is obvious that I believe that eric says: the sky is blue
我应该补充一点,pe = Professor('eric')
和ae = ArrogantProfessor('eric')
更改基本上是在开头添加Prof.
标题,因此它对所有方法都是通用的。因此我尝试添加类似" title"到self.name
课程__init__
方法中的Person(object)
- 但没有成功。有没有人有更好的主意谢谢!
答案 0 :(得分:0)
class Professor(Person):
def __init__(self, name):
self.name = 'Prof. ' + name
按照要求回答你的问题
可能你想要这样的东西:
Professor
然后只有__init__
(和它的子类)才会继承'教授'。标题。
此问题的关键是覆盖function chunk(\Generator $generator, $n) {
for ($i = 0; $generator->valid() && $i < $n; $generator->next(), ++$i) {
yield $generator->current();
}
}
function foo() {
for ($i = 0; $i < 11; ++$i) {
yield $i;
}
}
for ($gen = foo(); $gen->valid();) {
$chunk = [];
foreach (chunk($gen, 3) as $value) {
$chunk[] = $value;
}
print json_encode($chunk) . "\n";
}
答案 1 :(得分:0)
如果您需要方法ArrogantProfessor.say()
继承方法Professor.say()
,稍微改变其输出,则必须更改两个类中的方法say()
。
在Professor.say()
中,您可以添加标题“教授”,在ArrogantProfessor.say()
中,您必须通过say()
调用父方法super()
。
class Professor(Lecturer):
def say(self, stuff):
return 'Prof. ' + self.name + ' says: ' + self.lecture(stuff)
class ArrogantProfessor(Professor):
def say(self, stuff):
return super(ArrogantProfessor, self).say(stuff)
def lecture(self, stuff):
return 'It is obvious that ' + Lecturer.lecture(self, stuff)
我建议您查看有关继承的文档和super()
。
如Ben Jarrett所述,您也可以修改Professor.\__init__()
方法而不是上述方法,但在这种情况下,您的输出将变为:
Prof. eric says: I believe that Prof. eric says: the sky is blue Prof. eric says: It is obvious that I believe that Prof. eric says: the sky is blue