python之封装、组合

'''
1、什么是封装?
    封装指的是将一堆属性和方法,封装到对象中。
    ps:存不是目的,目的是为了取。封装是为了更好的获取。
    ps:对象就相当于一个封装的容器

2、为什么要封装?
    可以通过“对象”来“存放或获取”属性和方法
    方便数据的存取
    好比:一个铅笔盒里,存放着与写字有关的工具,而不会存放其他东西。
    当我们需要写字时会优先考虑到铅笔盒里选取工具

3、如何封装?
    通过类来封装,关键字class

'''
'''
1.什么是组合
    组合指的是一个对象中,包含另一个或多个对象。
2.为什么要使用组合
    减少代码的冗余
3.如何使用组合
'''
class People:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender


class Student(People):
    def __init__(self, name, age, gender):
        super().__init__(name, age, gender)


class Teacher(People):
    def __init__(self, name, age, gender):
        super().__init__(name, age, gender)

    def tell_birth(self):
        print(f'{self.name}出生于{self.birth_obj.year}年{self.birth_obj.month}月{self.birth_obj.day}日')


class Birth:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def tell_birth(self):
        print(f'{self.year}年{self.month}月{self.day}日')


t1_obj = Teacher('tank', 19, 'male')
birth_obj = Birth('1995', '2', '30')

# 为t1_obj添加birth属性,属性值是一个对象
t1_obj.birth_obj = birth_obj
t1_obj.tell_birth()

猜你喜欢

转载自www.cnblogs.com/Ghostant/p/11951072.html