组合与反射以及面向对象的内置函数
组合
1、概念
组合就是一个对象拥有一个属性,该属性的值是另外一个对象
2、作用
解决类与类之间的代码冗余问题
3、代码
class People(): school = 'SH' def __init__(self, name, age, gender, ): self.name = name self.age = age self.gender = gender class Admin(People): pass class Course(): def __init__(self, name, period, price, ): self.name = name self.period = period self.price = price python = Course('python', '6mon', 10000) linux = Course('linux', '5mon', 20000) class Student(People, Course): def __init__(self, name, age, gender, course=None): if course is None: course = [] self.courses = course super().__init__(name, age, gender, ) def choose_course(self, stu_obj, course): stu_obj.courses.append(course) class Teacher(People, Course): def __init__(self, name, age, gender, level): self.level = level super().__init__(name, age, gender, ) def score(self, stu_obj, score): stu_obj.score = score tea = Teacher('tony', 19, 'male', 10) tea.course = linux print(tea.course.name) print(tea.course.price) print(tea.course.period)
面向对象的内置函数
1、__init__
class Student(): school = 'SH' # 调用类的时候触发 def __init__(self, name, age): self.name = name self.age = age def tell(self): print('name: %s, age: %s' % (self.name, self.age))
2、__str__
# 打印对象的时候,自动触发的函数 # 返回值只能是字符串 def __str__(self): return 'name:%s' % self.name # return 123
3、__del__
# 1. 手动执行del # 2. 程序执行完毕触发 def __del__(self): print('__del__') self.f.close()
4、__call__
# 对象加括号自动触发 def __call__(self, *args, **kwargs): print('__call__')
反射
1、概念
对象通过字符串来操作属性
2、getattr(获取属性)
print(getattr(stu, 'name1', None)) # stu.name stu.func() print(getattr(stu, 'func')) getattr(stu, 'func')() # 必须掌握
3、setattr(赋值属性)
setattr(stu, 'x', 123) print(stu.__dict__)
4、hasattr(判断对象是否存在)
print(hasattr(stu, 'name'))
5、delattr(删除属性)
delattr(stu, 'name') print(stu.__dict__)