Day25

时间:2019-08-28
本文章向大家介绍Day25,主要包括Day25使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

类的使用

类的组合

什么是组合:

  • 对象的某个属性是另一个对象

组合的概念

class Foo:
    def __init__(self,bar):
        self.bar=bar

class Bar:
    pass

# f=Foo()
bar=Bar()
# f=Foo(Bar())
f=Foo(bar)

为什么要使用组合

组合可以减少代码的冗余

多态和多态性

什么是多态
  • 一类事物的多种形态
什么是多态性
  • 多态性是指在不考虑实例类型的情况下使用实例

好处:

​ 1.增加程序灵活性

​ 2.增加程序可扩展性

举例:

动物类:猪,狗,人

动物类细分后猪类,人类,狗类后,由于三类中都会有发声这个类,但是叫声由于三个类都各不相同,但是我们可以在动物类中定义一个叫声方法。

一、通过接口来实现统一化,约束代码
  #多态基础
class Animal:
    def speak(self):
        pass

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

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

class People(Animal):
    def speak(self):
        print('say hello')

pig=Pig()
dog=Dog()
people=People()
# pig.speak()
# dog.speak()
# people.speak()
二、通过装饰器来约束代码
在使用第二种方法是需要导入abc模块
  #第二在要约束的方法上,写abc.abstractmethod装饰器
    @abc.abstractmethod
    def speak(self):
        pass

在其他语言中会有规定的约束方法,但是在python中,由于语言崇尚自由,所以并没有明确的约束条件,在python中多使用鸭子类型,就是只要这个类里面有这个绑定方法,那么就是鸭子。

另外的解决方式:

上述提到,python中崇尚鸭子类型,那么在实际开发中,我不同的类里面想实现同一种方法其实并不用继承父类,只要里面有这个方法就行了,那么如果没有这个方法,那么我们就无法利用python中的多态性了

class Pig(Animal):
    def speak(self):
        print('哼哼哼')
class Dog(Animal):
    def yy(self):
        print('汪汪')
class People(Animal):
    def zz(self):
        print('say hello')
people = People()
people.zz()
##这样就不能利用多态性
def animal_speak(obj):
    obj.speak()
pig=Pig()
通过异常处理来实现(常用)
class Animal():
    def speak(self):
        #主动抛出异常
        raise Exception('你得给我重写它啊')
class Pig(Animal):
    def speak(self):
        print('哼哼哼')
class People(Animal):
    def speak(self):
        print('say hello')
pig=Pig()
pe=People()
def animal_speak(obj):
    obj.speak()

animal_speak(pig)
animal_speak(pe)

封装

什么是封装

从封装本身的意思上来看,就是把拿一个袋子或者可以装容器的东西,将一些东西放进去。

比如:我出门去买菜,买肉,那么我购买来的这些东西,我需要拿塑料袋把他装起来,这个其实就是封装

如何用代码实现隐藏

隐藏属性/隐藏方法 隐藏之后,外部访问不到,只有内部能够访问

  • **__隐藏属性**:通过 __变量名来隐藏

  • **__隐藏方法**:通过 __方法名来隐藏name

隐藏起来隐藏属性是为了安全

class Person:
    def __init__(self,name,age):
        self.__name=name
        self.__age=age
    def get_name(self):
        # print(self.__name)
        return '[----%s-----]'%self.__name

p=Person('nick',89)
print(p.age)

@property

class Person:
    def __init__(self,name,height,weight):
        self.__name=name
        self.__height=height
        self.__weight=weight
    @property
    def name(self):
        return '[我的名字是:%s]'%self.__name
    #用property装饰的方法名.setter
    @name.setter
    def name(self,new_name):
        # if not isinstance(new_name,str):
        if type(new_name) is not str:
            raise Exception('改不了')
        if new_name.startswith('sb'):
            raise Exception('不能以sb开头')
        self.__name=new_name

    # 用property装饰的方法名.deleter
    @name.deleter
    def name(self):
        # raise Exception('不能删')
        print('删除成功')
        # del self.__name

原文地址:https://www.cnblogs.com/ledgua/p/11425206.html