我有一个名为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 :(得分: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.count
(来自self.count
,如果您只读,则会有效。但只要您将某些内容分配给self.count
,更改只会影响实例self
而不是类)。在super().__init__()
中调用MathStudentBody
也会增加StudentBody.count
。
(Body.count
......轻笑!)