Atopos

导航

组合、面向对象的内置函数及反射

1.组合

image

1.1组合的定义

image

一个对象的属性值是指向于另一个类的对象

1.2组合的使用示例

image

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)

2.面向对象的内置函数

image

1.__init__()
eg:
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.__exit__()
pass


5.__enter__()
pass



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


stu = Student('ly', 20)

3.反射

image

对象通过字符串来操作属性
四个操作方法
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__)

image

posted on 2021-12-07 19:09  Atopos_q  阅读(4)  评论(0编辑  收藏  举报