2016-11-01 3 views
-2

私の問題は説明するのが少し難解です。私に例を示してみましょう。私は、次の取得するようグローバルに使用するクラスを変更する方法

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.タイトルを追加することで、すべてのメソッドで共通です。したがって、Person(object)クラスの__init__メソッド内のself.nameに「タイトル」のようなものを追加しようとしましたが、成功しませんでした。誰かが良いアイデアを持っていますありがとう!あなたが何かしたいのにおそらく

を尋ねたとして、あなたの質問に答える

+0

私は理解していませんあなたが実際に求めていること。ここでのあなたの「質問」の大部分は、あなたの宿題です。あなたが問題を抱えているのではありません。自分のコードを表示していないので、何がうまくいかないのかわかりません! – Blckknght

答えて

0
class Person(object):  
    def __init__(self, name):   
     self.name = 'Prof. ' + name 

class Professor(Person): 
    def __init__(self, name): 
     self.name = 'Prof. ' + name 
その後

のみProfessor(およびそのサブクラス)は、「教授」を継承しますタイトル。

この問題の鍵は、あなたが少しその出力を変化させながら、方法Professor.say()から継承するメソッドArrogantProfessor.say()が必要な場合は、両方のクラスにメソッドsay()を変更する必要があります__init__

0

を上書きしています。 Professor.say()

、あなたは、タイトル「教授」を追加することができますし、ArrogantProfessor.say()に、あなたはsuper()経由で親メソッドsay()を呼び出す必要があります。

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 
関連する問題