面向对象编程day3

组合

1. 什么是组合
一个对象的属性是来自于另外一个类的对象,称之为组合

2. 为何用组合
组合也是用来解决类与类代码冗余的问题

class OldboyPeople:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender


class OldboyStudent(OldboyPeople):
course = []

def choose_course(self, course):
self.course.append(course)
def check_courese(self):
for i in self.course:
print('<课程:%s 学时:%s 学费:%s>' %(i.name,i.period,i.cost))


class Course:
def __init__(self, name, period, cost):
self.name = name
self.period = period
self.cost = cost


Python = Course('Python全栈开发', '5mons', 3888)
linux=Course('linux运维','5mons',3777)
stu1 = OldboyStudent('qqq', 17, 'male')
stu1.choose_course(Python)
stu1.choose_course(linux)
stu1.check_courese()

封装

1. 什么是封装
装指的是把属性装进一个容器
封指的是隐藏的意思,但是这种隐藏式对外不对内的

2. 为何要封装
封装不是单纯意义的隐藏
封装数据属性的目的:将数据属性封装起来,类外部的使用就无法直接操作该数据属性了
需要类内部开一个接口给使用者,类的设计者可以在接口之上附加任意逻辑,从而严格
控制使用者对属性的操作
封装函数属性的目的:隔离复杂度

3. 如何封装
只需要在属性前加上__开头,该属性就会被隐藏起来,该隐藏具备的特点:
1. 只是一种语法意义上的变形,即__开头的属性会在检测语法时发生变形_类名__属性名(原理)
2. 这种隐藏式对外不对内的,因为在类内部检测语法时所有的代码统一都发生的变形
3. 这种变形只在检测语法时发生一次,在类定义之后新增的__开头的属性并不会发生变形
4. 如果父类不想让子类覆盖自己的属性,可以在属性前加__开头

Property装饰器

可无须在对象绑定方法后加括号.

class People:
def __init__(self,name,weight,height):
self.name=name
self.weight=weight
self.height=height

@property
def bmi(self):
return self.weight / (self.height ** 2)

obj=People('egon',70,1.82)
obj.height=1.85

print(obj.bmi)
需要了解的property的用法
class People:
def __init__(self,name):
self.__name=name

@property
def name(self):
return '<name:%s>' %self.__name

@name.setter
def name(self,new_name):
if type(new_name) is not str:
print('名字必须是str类型')
return
self.__name=new_name

@name.deleter
def name(self):
del self.__name

obj=People('egon')
print(obj.name)

# obj.name=123
# print(obj.name)

del obj.name
print(obj.__dict__)

多态

1. 什么是多态
同一种事物的多种形态

2. 为何要用多态
多态性:指的是可以在不用考虑对象具体类型的前提下而直接使用对象下的方法

 

通过父类强制规定子类必须要包含父类中的函数名,但不推荐,一般都是约定俗成.

import abc

class Animal(metaclass=abc.ABCMeta):
@abc.abstractmethod
def speak(self):
pass

# Animal() # 父类不能实例化,因为父类本身就是用来制定标准的
class People(Animal):
def speak(self):
print('say hello')
# def jiao(self):
# print('say hello')

class Dog(Animal):
def speak(self):
print('汪汪汪')

class Pig(Animal):
def speak(self):
print('哼哼哼')


peo=People()
dog1=Dog()
pig1=Pig()
#
#
peo.speak()
dog1.speak()
pig1.speak()





posted @ 2018-10-24 20:09  endlesswaltz  阅读(100)  评论(0编辑  收藏  举报