python-面向对象(四)

组合

什么是组合:组合指的是一个对象中,包含另一个对象。
为什么要用组合:减少代码冗余
组合的使用:

class People:
    def __init__(self, name, age, male):
        self.name = name
        self.age = age
        self.male = male


class Course:
    def __init__(self, course_name, course_price, course_time):
        self.course_name = course_name
        self.course_price = course_price
        self.course_time = course_time

    def course_info(self):
        print('''
        课程名称: %s
        课程价格: %s
        课程时间: %s
        ''' % (self.course_name, self.course_price, self.course_time))


class Student(People):
    def __init__(self, name, age, male):
        super().__init__(name, age, male)
        self.course_list = []

    def tall_all_course(self):
        for course_all in self.course_list:
            course_all.course_info()  # 循环打印 Course.course_info


c1 = Course('python', '30000', '6mon')
c2 = Course('go', '30000', '5mon')
s1 = Student('jason', 18, 'male')
s1.course_list.append(c1)  # 追加进去的是c1对象
s1.course_list.append(c2)
s1.tall_all_course()

面向对象内置函数

class Student:
    def __init__(self, name, age):  # 执行时触发
        self.name = name
        self.age = age

    def __str__(self):  # 打印对象时触发 print(s1)  
        return 'name: %s' % self.name  # 返回值只能是字符串

    def __call__(self, *args, **kwargs):  # 对象加括号触发 s1()
        print('__call__')

    def __del__(self):  # 程序执行完毕触发
        print('__del__')


s1 = Student('jason', 18)
print(s1)
s1()

with上下文管理

class A:
    def __enter__(self):
        print('__enter__() is called')
 
    def __exit__(self, e_t, e_v, t_b):
        print('__exit__() is called')
 
 
with A() as a:
    print('got instance')

反射

# 对象通过字符串来操作属性

1. getattr
print(getattr(stu, 'name1', None))  # stu.name
stu.func()
print(getattr(stu, 'func'))
getattr(stu, 'func')()  # 必须掌握

2. setattr
setattr(stu, 'x', 123)
print(stu.__dict__)

3. hasattr
print(hasattr(stu, 'name'))

4. delattr
delattr(stu, 'name')
print(stu.__dict__)

异常

1. 什么是异常?
	异常就是错误发生的信号,如果不对该信号做处理,那么异常之后的代码都不会执行

    异常的种类:
    	1. 语法错误
        	print(123
        2. 逻辑错误
             # 逻辑错误尽量写到完美
			a = [1, 2, 3]
             a[5]
2. 为什么要用异常
	增强代码的健壮性
                  
3. 怎么用异常?
        try:
              被监测代码
        except 异常的类型:
                  pass
          except 异常的类型:
                  pass
          except 异常的类型:
                  pass
        except Exception as e:
                  pass
        else:
              # 当被监测代码没有发生异常的时候,触发的
                  pass
        finally:
               不管被监测的代码有没有出错,都执行  
posted @ 2021-12-07 19:08  klcc-cc  阅读(35)  评论(0)    收藏  举报