找出学生总数

2024-04-20 07:34:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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

Tags: nameselfreturninitdefcountgenderyear
1条回答
网友
1楼 · 发布于 2024-04-20 07:34:32

你的意思是这样的(把代码精简到最低限度…)

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,而不会影响类)。在MathStudentBody中调用super().__init__()也会增加StudentBody.count。你知道吗

^{}。。。咯咯笑!)你知道吗

相关问题 更多 >