-
类的定义与使用
class Student():
name = ''
age = 0
def print_file(self):
print('name: ' + self.name)
print('age: ' + str(self.age))
from Test.t1 import Student
student = Student()
student.print_file()
-
成员
变量
1. 类变量 2. 实例变量
方法
1. 构造函数 2. 实例方法 3. 类方法 4. 静态方法
成员的可见性
私有成员:变量名或方法名前加双下划线
class Student():
# 类变量
sum = 0
# 构造函数,初始化对象的属性
def __init__(self, name, age):
# 实例变量
self.name = name
self.age = age
# 在实例方法中操作类变量的方法
# self.__class__.sum += 1
# print('当前班级学生总数为:'+str(self.__class__.sum))
# 私有成员 __score
self.__score = 0
def do_homework(self):
print('homework')
# 类方法
@classmethod # 装饰器
def plus_sum(cls):
cls.sum += 1
print('当前班级学生总数为:'+str(cls.sum))
# 静态方法
@staticmethod #装饰器
def add(x, y):
# 静态方法内部访问类变量
print(Student.sum)
print('This is a static method')
def marking(self,score):
if score < 0:
return '分值不能为负'
self.__score = score
print(self.name + '同学分数为:' + str(self.__score))
student1 = Student('小黑', 18)
# Student.plus_sum()
# student2 = Student('小白', 18)
# Student.plus_sum()
# student3 = Student('小黑', 18)
# Student.plus_sum()
# student1.add(1, 2)
# Student.add(1, 2)
student1.marking(95)
print(student1.__dict__)
'''
打印结果为{'name': '小黑', 'age': 18, '_Student__score': 95} __score已被更名保护
'''
-
继承
# Human类为Student类的父类
class Human():
sum = 0
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
print(self.name)
def do_homework(self):
print('This is a parent method')
from Test.t4 import Human
class Student(Human):
def __init__(self, school, name, age):
self.school = school
# 显示调用父类构造函数
# Human.__init__(self, name, age)
# 使用super关键字调用父类构造方法
super(Student, self).__init__(name, age)
def do_homework(self):
# 使用super关键字调用父类实例方法
super(Student, self).do_homework()
print('do homework')
student1 = Student('人民路小学', '小黑', 18)
# print(student1.name)
# print(student1.age)
# print(student1.sum)
# print(Student.sum)
# student1.get_name()
student1.do_homework()