创建类的实例

  1. # 创建类的对象(实例化类)
  2. # python中实例化类不需要使用关键字new(也没有这个关键字),类的实例化类似函数调用方式。
  3. student1 = Student('cuiyongyuan',10)
  4. student2 = Student('yuanli', 10)
  5. student1.display_student()
  6. student2.display_student()
  7. student1_class = student1.get_class()
  8. student2_class = student2.get_class()

类的定义

  1. # coding: utf-8
  2. # 创建一个类,类名称第一个字母大写,可以带括号也可以不带括号
  3. class Student():
  4. student_count = 0
  5. def __init__(self, name, salary):
  6. self.name = name
  7. self.age = salary
  8. Student.student_count += 1
  9. def display_count(self):
  10. print('Total student {}'.format(Student.student_count))
  11. def display_student(self):
  12. print('Name: {}, age: {}'.format(self.name,self.age))
  13. def get_class(self):
  14. if self.age >= 7 and self.age < 8:
  15. return 1
  16. if self.age >= 8 and self.age < 9:
  17. return 2
  18. if self.age >= 9 and self.age < 10:
  19. return 3
  20. if self.age >= 10 and self.age < 11:
  21. return 4
  22. else:
  23. return 0