2017-01-20 8 views
0

私はStudentBodyという親クラスとMathStudentBodyという子クラスを持っています。私の質問は、クラス内の生徒の総数を見つけるために、どのように子クラスを説明することができるのですか?私は作成されたオブジェクトの総数を調べなければならないと思いますか?あなたはこのような何かを意味生徒の総数を確認

class StudentBody: 

    count = 0 
    def __init__(self, name,gender,year,gpa): 
     self.name = name 
     self.gender = gender 
     self.year = year 
     self.gpa = gpa 
     self.count+= 1 

    def IsFreshman(self): 
     print "I am the StudentBody method" 
     if self.year == 1: 
      return True 
     else : 
      return False 

    def countTotal(self): 
     return self.count 

class MathStudentBody(StudentBody): 

    def __init__(self,name,gender,year,gpa,mathSATScore): 
     #super(MathStudentBody,self).__init__(name,gender,year,gpa) 
     StudentBody.__init__(self,name,gender,year,gpa) 
     self.MathSATScore = mathSATScore 

    def IsFreshman(self): 
     print "I am the MathStudentBody method" 


    def CombinedSATandGPA(self): 
     return self.gpa*100 + self.MathSATScore 

    def NumberOfStudents(self): 
     return 
+0

あなたは 'self.count + = 1 'を呼び出し、これは失敗しないのですか? –

+0

@WillemVanOnsem:いいえ、それは 'StudentBody.count'にアクセスするだけです。 –

答えて

1

誰もが、私はクラス変数へのアクセスを変更

class StudentBody: 
    count = 0 
    def __init__(self): 
     StudentBody.count+= 1 

class MathStudentBody(StudentBody): 
    count = 0 
    def __init__(self): 
     super().__init__()      # python 3 
     # super(MathStudentBody, self).__init__() # python 2 
     MathStudentBody.count+= 1 

s = StudentBody() 
ms = MathStudentBody() 

print(StudentBody.count) # 2 
print(MathStudentBody.count) # 1 

ノートを(...最低限にあなたのコードをストリップダウン)正しい方向に私を指すことができますStudentBody.countself.countから読み取り専用の場合は動作しますが、self.countに何かを割り当てるとすぐに、変更はインスタンスselfに影響し、クラスには影響しません)。 MathStudentBodysuper().__init__()を呼び出すと、StudentBody.countも増加します。

Body.count ...含み笑い!)あなたのコードで

関連する問題