19 面向对象 04
目录:
1.组合:
2.mixins机制(了解)
3.内置函数
4.反射
5.异常
一、组合
组合:一个对象拥有一个属性, 属性的值必须是另外一个对象
# class Foo: # def __init__(self, m): # self.m = m # # # class Bar(): # def __init__(self, n): # self.n = n # # # obj = Foo(10) # print(obj.m) # # # obj1 = Bar(20) # # print(obj1.n) # # obj.x = obj1 # print(obj.x.n) # 案例 class People(): school = 'SH' def __init__(self, name, age, gender, course=None): if course is None: course = [] self.name = name self.age = age self.gender = gender self.courses = course # class Admin(People): # pass class Course(): def __init__(self, course_name, course_period, course_price): self.course_name = course_name self.course_period = course_period self.course_price = course_price python = Course('python', '5mon', 1000) linux = Course('linux', '6mon', 2000) # print(python.course_name) # print(python.course_period) # print(python.course_price) # print(linux.course_name) # print(linux.course_period) # print(linux.course_price) class Student(People): school = 'SH' def __init__(self, name, age, gender, course_name, course_period, course_price, course=None): if course is None: course = [] self.courses = course super().__init__(name, age, gender) def choose_course(self, course): self.courses.append(course) print("%s选课成功%s" % (self.name, self.courses)) stu = Student('egon', 18, 'male', 'python', '6mon', 1000) # 让学生类拥有课程 # courses = ['python', 'linux'] # courses = [<__main__.Course object at 0x000002AA4893BFD0>, <__main__.Course object at 0x000002AA4893BFD0>] # stu.courses.append(python.course_name) # stu.courses.append(python) # stu.courses.append(linux) # for i in stu.courses: # print(i.course_name) class Teacher(People): school = 'SH' def __init__(self, name, age, gender, level=None): self.level = level super().__init__(name, age, gender) def score(self, stu_obj, score): stu_obj.score = score print("%s给%s打%s分" % (self.name, stu_obj.name, score)) tea = Teacher('egon', 18, 'male') tea.course = python print(tea.course.course_name)
二、mixins机制(辅类放在主类的左边)
class Vehicle: # 交通工具 def run(self): pass def run1(self): pass def run2(self): pass def run3(self): pass def run4(self): pass class FlyMixin(): # class Flyable(): def fly(self): ''' 飞行功能相应的代码 ''' print("I am flying") class CivilAircraft(FlyMixin, Vehicle): # 民航飞机 pass class Helicopter(FlyMixin, Vehicle): # 直升飞机 pass class Car(Vehicle): # 汽车并不会飞,但按照上述继承关系,汽车也能飞了 pass import socketserver
3.内置函数
# class Student(): # school = 'SH' # # # 1. 打印对象会自定触发的函数,方法 # # 2. 返回值必须是字符串类型 # # def __str__(self): # # return self.school # return 123 # # # # def index(self): # # return self.school # # stu = Student() # print(stu) ###########__del__################ # class Student(): # school = 'SH' # # def __init__(self): # self.f = open('xxx', mode='w') # # # 1. 删除对象属性的时候,自动触发 # # 2. 当所有代码执行完成之后,还会自动触发 # def __del__(self): # print("__del__") # self.f.close() # # # stu = Student() # # # stu.x = 1 # # del stu.x # # print("end=====>") ###########__del__################ # 补充: # a = 123 # int(123) # s = str('abc') # print(type(s) is str) # print(isinstance(s, int)) # class Foo: # pass # # print(issubclass(Foo, object)) # class Foo: # x = 1 # # def __init__(self, y): # self.y = y # # # 当访问一个不存在的属性时候,会自定触发 # def __getattr__(self, item): # print('----> from getattr:你找的属性不存在') # # def __setattr__(self, key, value): # print('----> from setattr') # # print(key) # # print(value) # # self.key = value # 这就无限递归了,你好好想想 # self.__dict__[key] = value # 应该使用它 # # def __delattr__(self, item): # print('----> from delattr') # # del self.item #无限递归了 # self.__dict__.pop(item) # # # obj = Foo(10) # obj.z = 10 # 必须掌握 #################################__call__########################### class Foo: def __init__(self): pass # 当给对象加括号时候,自定触发的函数 def __call__(self, *args, **kwargs): print('__call__') obj = Foo() # 执行 __init__ obj() # obj.x = 1 # obj.'x' = 1
4.反射
# # class Foo: # school = 'SH' # # # obj = Foo() # x = input(":>>").strip() # school => str # print(obj.x) # print(obj.'school') # 反射:掌握反射中的四个方法即可 # 1. # print(getattr(obj, x)) # print(getattr(obj, 'school')) # print(getattr(obj, 'school1', 'SH')) # print(getattr(obj, 'school', 'SH111')) # 2. 字符串形式设置属性 # setattr(obj, 'y', 10) # print(obj.__dict__) # 3. # delattr(Foo, 'school') # print(Foo.__dict__) # 4. 如何判断是否有这个属性 # print(hasattr(obj,'school')) ##################################超级重要############################# # class Foo: # school = 'SH' # # def func(self): # print("func") # obj = Foo() # # getattr(obj, 'func')() # # print(getattr(obj, 'func')) # # hander = getattr(obj, 'func', None) # # # def test(*args, **kwargs): # return hander(*args, **kwargs) # # test() # import time # # time.sleep(3) # # getattr(time, 'sleep')(3) # import time time = __import__('time') time.sleep(3)
5.异常
# print(123) # x = 1 # print(x) # # a = [1, 2, 3] # # if len(a) >= 2: # a[2] # else: # print("错误") # # try: # x = 1 # except IndexError as e: # pass # except IndexError as e: # pass # except IndexError as e: # pass # else: # print("123") # finally: # print("123") # NameError # print(x) # IndexError # a = [1, 2] # a[3] # AttributeError # class Foo: # pass # obj = Foo() # # obj.x # TypeError # for i in 123: # pass # ZeroDivisionError # 1/0 # try: # a = [1, 2, 3] # # print(a) # # a[5] # 1/0 # except IndexError as e: # print(e) # except AttributeError as e: # print(e) # except ZeroDivisionError as e: # print(e) # # else: # print("这是else") # finally: # print("这是finally") # try: # pass # except: # pass # # try: # pass # else: # pass # # try: # pass # # finally: # pass # # try: # pass # except: # pass # else: # pass a = [1, 2, 3] # if len(a) >= 5: # print(123) # else: # # print("索引错误") # # return # # break # raise Exception("索引错误") # 断言 # 单元测试 # assert len(a) == 5 # print("end----") # class Animal(): # def speak(self): # raise Exception("必须实现speak方法") # # # class People(Animal): # pass # # # obj = People() # # obj.speak() # 自定义异常类【 class MyException(BaseException): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg raise MyException("这是自定义异常类")