Python 找出学生总数
我有一个名为StudentBody的父类和一个名为MathStudentBody的子类。我的问题是,我如何解释儿童班,以便找出班上的学生总数?我想我们必须找出创建的对象的总数?谁能给我指一下正确的方向吗Python 找出学生总数,python,inheritance,Python,Inheritance,我有一个名为StudentBody的父类和一个名为MathStudentBody的子类。我的问题是,我如何解释儿童班,以便找出班上的学生总数?我想我们必须找出创建的对象的总数?谁能给我指一下正确的方向吗 class StudentBody: count = 0 def __init__(self, name,gender,year,gpa): self.name = name self.gender = gender self.y
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
你的意思是像这样把你的代码精简到最低限度
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
请注意,我将对类变量的访问权限从self.count更改为StudentBody.count,如果您是只读的,则可以使用self.count。但是,一旦您将某些内容分配给self.count,更改只会影响实例self,而不会影响类。在MathStudentBody中调用super.\uuuuu init\uuuuu也会增加StudentBody.count
。。。咯咯笑 在您的代码中,您将self.count+=1,这不会失败吗?@WillemVanOnsem:不会,这将只访问StudentBody.count。