Instance attributes and class attributes

Exercise
In order to count the number of students, you can add a class attribute to the Student class. Each time an instance is created, the attribute will automatically increase:

# -*- coding: utf-8 -*-

class Student(object):
    count = 0

    def __init__(self, name):
        self.name = name
        Student.count+=1

# test:
if Student.count != 0:
    print('Test failed!')
else:
    bart = Student('Bart')
    if Student.count != 1:
        print('Test failed!')
    else:
        lisa = Student('Bart')
        if Student.count != 2:
            print('Test failed!')
        else:
            print('Students:', Student.count)
            print('Test passed!')

  The count class attribute cannot be directly referenced in the function of the class, and Student.count is required

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325113990&siteId=291194637