类的组合与封装

组合

1.什么是组合?

  组合指的是一个对象中,包含另一个或多个对象。

2.为什么要用组合?

  减少代码的冗余

3.如何使用组合?

  耦合度:

  藕:莲藕---->藕断丝连

  • 耦合度越高:程序的可扩展性越低

  • 耦合度越低:程序的可扩展性越高

      • 总结:

          -继承:

          继承是类与类的关系,子类继承父类的属性/方法,子类与父类是一种“从属”关系。

        -组合:

          组合是对象与对象的关系,一个对象拥有另一个对象中的属性/方法,是一种什么有什么的关系

#继承
#父类
class People:
    def __init__(self,name,age,sex,year,mouth,day):
        self.name = name
        self.age = age
        self.sex = sex
        self.year = year
        self.mouth = mouth
        self.day = day
    
        def tell_birth(self):
        print(f'''
        ===== 出生年月日 =====
            年: {self.year}
            月: {self.month}
            日: {self.day}
        ''')


# 老师类
class Teacher(People):
    def __init__(self, name, age, sex, year, month, day):
        super().__init__(name, age, sex, year, month, day)


# 学生类
class Student(People):
    def __init__(self, name, age, sex, year, month, day):
        super().__init__(name, age, sex, year, month, day)


tea1 = Teacher('tank', 17, 'male', 2002, 6, 6)
stu1 = Student('HCY', 109, 'female', 1910, 11, 11)

print(tea1.name, tea1.age, tea1.sex)
tea1.tell_birth()
print(stu1.name, stu1.age, stu1.sex)
stu1.tell_birth()

# 组合实现
class People:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex


# 老师类
class Teacher(People):
    def __init__(self, name, age, sex):
        super().__init__(name, age, sex)


# 学生类
class Student(People):
    def __init__(self, name, age, sex):
        super().__init__(name, age, sex)



# 日期类
class Date:
    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}
        ''')


# tea1 = Teacher('tank', 17, 'male', 2002, 6, 6)
# print(tea1.name, tea1.age, tea1.sex)
# tea1.tell_birth()
# tea1 = Teacher('tank', 17, 'male')
# stu1 = Student('HCY', 109, 'female', 1910, 11, 11)



stu1 = Student('HCY', 109, 'female')
date_obj = Date(1910, 11, 11)
# 学生对象中包含一个自定义日期对象
stu1.date_obj = date_obj
# print(stu1.name, stu1.age, stu1.sex)
# print(stu1.date_obj.year, stu1.date_obj.month, stu1.date_obj.day)
stu1.date_obj.tell_birth()

封装

1.什么是封装?

  封:比如将一个袋子,封起来

  装:比如将一堆小猫、小狗和jason装在袋子里。

  #对象--->相当于一个袋子

封装指的是可以将一堆属性和方法,封装到对象中。

  ps:对象就好比一个“袋子/容器”,可以存放一对属性和方法

  ps:存不是目的,目的是为了取,可以通过“对象.”的方式获取属性或方法。

2.为什么封装?

  可以通过“对象.”的方式“存放/获取”属性或方法。

  对象拥有“.”的机制

  方便数据的存取。

3.如何封装

 class User:
            x = 10
            def func():
                pass
        obj = User()
        obj.y = 20
        obj ---> x, func, y

 

原文地址:https://www.cnblogs.com/lvguchujiu/p/11944553.html