学习Python(12)封装&继承&多态&类方法和静态方法&类中的常用属性&单例设计模式

目录

  • 学习Python(12)封装&继承&多态&类方法和静态方法&类中的常用属性&单例设计模式
    • 一.封装
      • 1.概念
      • 2.私有属性和私有方法
      • 3.@property装饰器
    • 二.继承
      • 1.单继承
      • 2.多继承
      • 3.函数重写
    • 三.多态
    • 四.类方法和静态方法
    • 五.类中的常用属性和方法
    • 六.单例设计模式

学习Python(12)封装&继承&多态&类方法和静态方法&类中的常用属性&单例设计模式

一.封装

1.概念

广义的封装:
函数和类的定义本身,就是封装的体现

狭义的封装:
一个类的某些属性,在使用的过程 中,不希望被外界直接访问,而是把这个属性给作为私有的【只有当前类持有】,然后暴露给外界一个访问的方法即可【间接访问属性】

封装的本质:
就是属性私有化的过程

封装的好处:
提高了数据的安全性,提高了数据的复用性

说明:
举例:插排,不需要关心属性在类的内部做了什么样的操作,只需要关心将值传进去,或者将结果获取出来

封装: 函数 => 类 => 模块 => 包

2.私有属性和私有方法

私有属性:
如果想让成员变量不被外界直接访问,则可以在属性名称的前面添加两个下划线__,成员变量则被称为私有成员变量

私有属性的特点:只能在类的内部直接被访问,在外界不能直接访问
私有方法
如果类中的一个函数名前面添加__,则认为这个成员函数时私有化的

特点:也不能在外界直接调用,只能在类的内类调用

# 类
class Person:
    def __init__(self, name, age, sex):
        self.name = name  # 公有属性
        self.__age = age  # 私有属性: 双下划线开头的属性, 只能在当前类内部使用
        self._sex = sex  # 公有属性,但是不建议这么写

    def run(self):
        print(self.__age)
        self.__eat()
        
    # 私有方法
    def __eat(self):
        print("eat")


# 对象
p = Person('鹿晗', 30, '男')
print(p.name)
# print(p.__age)  # 报错,__age是私有属性
print(p._sex)
p.run()
print()

# p.__eat()  # 报错,__eat()是私有方法

# 下面的方式可以调用私有属性或私有方法,但是不要这么用
# print(p._Person__age)
# p._Person__eat()

3.@property装饰器

1.装饰器的作用:
可以给函数动态添加功能,对于类的成员方法,装饰器一样起作用

2.Python内置的@property装饰器的作用:将一个函数变成属性使用

3.@property装饰器:简化get函数和set函数

4.使用:@property装饰器作用相当于get函数,同时,会生成一个新的装饰器@属性名.settter,相当于set函数的作用

5.作用:使用在类中的成员函数中,可以简化代码,同时可以保证对参数做校验


class Person:
    def __init__(self, name, wechat):
        self.name = name
        self.__wechat = wechat

    # # getter 间接获取私有属性
    # def get_wechat(self):
    #     return self.__wechat
    #
    # # setter 间接修改私有属性
    # def set_wechat(self, new_wechat):
    #     self.__wechat = new_wechat

    @property   # 作用:让wechat函数可以当成属性来调用
    def wechat(self):
        return self.__wechat

    @wechat.setter
    def wechat(self, new_wechat):
        self.__wechat = new_wechat

    @property
    def photo(self):
        s = self.name + self.__wechat
        return s


# 对象
p = Person('刘亦菲', '110')
# print(p.get_wechat())
#
# p.set_wechat('119')
# print(p.get_wechat())

print(p.wechat)
p.wechat = '120'
print(p.wechat)

print(p.photo)

二.继承

如果两个或者两个以上的类具有相同的属性或者成员方法,我们可以抽取一个类出来,在抽取的类中声明公共的部分

​ 被抽取出来的类:父类,基类,超类,根类

​ 两个或者两个以上的类:子类,派生类

​ 他们之间的关系:子类 继承自 父类

注意:

a.object是所有类的父类,如果一个类没有显式指明它的父类,则默认为object
b.简化代码,提高代码的复用性

1.单继承

简单来说,一个子类只能有一个父类,被称为单继承

语法:
父类:

class 父类类名(object):
	类体【所有子类公共的部分】

子类:

class 子类类名(父类类名):
	类体【子类特有的属性和成员方法】

说明:一般情况下,如果一个类没有显式的指明父类,则统统书写为object

# 父类: 基类
class Ipad(object):
    def __init__(self, price):
        self.price = price

    def movie(self):
        print('看电影')


# 子类: 派生类
class Iphone(Ipad):
    def __init__(self, price, color):
        # 需要调用父类的init方法: 对父类属性进行初始化
        # Ipad.__init__(self, price)  # 显式调用
        super().__init__(price)  # 隐式调用

        self.__color = color

# 子类
class Iwatch(Iphone):
    def __init__(self, price, color, size):
        super().__init__(price, color)
        self.size = size

    def health(self):
        print(self.price)
        # print(self.__color)  # 不能使用父类的私有属性和私有方法, 私有属性和私有方法不能继承

# 对象
# iphone = Iphone(7000, 'green')
# print(iphone.price, iphone.color)
# iphone.movie()

# iwatch = Iwatch(2000, 'yellow', '1.8')
# print(iwatch.price, iwatch.size)
# iwatch.movie()
# iwatch.health()

2.多继承

一个子类可以有多个父类

语法:

class 子类类名(父类1,父类2,父类3.。。。):
	类体
# 父类
class Father:
    def __init__(self, name):
        self.name = name

    def run(self):
        print("会跑步")


# 父类
class Mother:
    def __init__(self, age):
        self.age = age

    def cook(self):
        print("会做饭")


# 子类
class Son(Father, Mother):
    def __init__(self, name, age, height):
        # 显式调用
        Father.__init__(self, name)
        Mother.__init__(self, age)

        # 隐式调用
        # super().__init__(name)  #
        # super(Son, self).__init__(name)  # 继承Father
        # super(Father, self).__init__(age)  # 继承Mother

        self.height = height


# 对象
son = Son('哪吒', 8, 1)
print(son.name, son.age, son.height)
son.run()
son.cook()

# mro算法: 从左往右的继承链
print(Son.__mro__)
# (
#   ,
#   ,
#   ,
#   
# )

3.函数重写

在子类中出现和父类同名的函数,则认为该函数是对父类中函数的重写

# 重写: 方法重写

class Person:
    def __init__(self, name):
        self.name = name

    def jump(self):
        print("跳2米远")


class Player(Person):
    def __init__(self, name):
        super().__init__(name)

    # 把父类的jump方法重写了
    def jump(self):
        print("跳4米远")


# 对象
p = Person('宝强')
p.jump()

p2 = Player('姚明')
p2.jump()

系统函数重写

__str__   
__repr__
class Cat:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 1. 必须返回字符串
    # 2. 作用是让打印的对象的值是这里的返回值
    def __str__(self):
        return f'名字:{self.name},年龄:{self.age}'

    # def __repr__(self):
    #     return f'名字2:{self.name},年龄2:{self.age}'


cat = Cat('汤姆', 3)
print(cat)
# => <__main__.Cat object at 0x000001DF76C41908>
# => 名字:汤姆,年龄:3

print(repr(cat))

# str
print(str([1,2,3]))  # "[1, 2, 3]"

三.多态

一种事物的多种体现形式,函数的重写其实就是多态的一种体现

在Python中,多态指的是父类的引用指向子类的对象

# 父类
class Animal:
    def eat(self):
        pass


# 子类
class Dog(Animal):
    def eat(self):
        print("吃骨头")

class Cat(Animal):
    def eat(self):
        print("吃鱼")

class Cow(Animal):
    def eat(self):
        print('吃草')

#
class Person:
    def __init__(self, name):
        self.name = name

    def keep(self, animal):
        print(f'{self.name}养了一只小动物')
        animal.eat()


# 创建对象
dog = Dog()
cat = Cat()
cow = Cow()

p = Person('小明')
p.keep(dog)

四.类方法和静态方法

类方法:@classmethod

  1. 可以用类和对象调用, 推荐用类调用,可以节省内存
  2. 类方法内部是不可以使用对象属性和其他成员方法或私有方法,
  3. 类方法内部可以使用其他 类方法或类属性

静态方法:@staticmethod

  1. 可以用类和对象调用, 推荐用类调用,可以节省内存
  2. 静态方法内部是不可以使用对象属性和其他成员方法或私有方法,
  3. 也不建议去使用类属性和类方法, 一般写成静态方法的就是一个普通函数,只是放在类里面
class Dog:
    age = 2

    def __init__(self, name):
        self.name = name

    def run(self):
        print("成员方法/公有方法")

    def __eat(self):
        print("私有方法: 只能在当前类内部使用")

    @classmethod
    def sleep(cls):  # cls: class
        print("类方法:", cls==Dog)  # True
        print(cls.age)  # 调用类属性

    @staticmethod
    def swim():
        print('静态方法')


# 对象
d = Dog('哮天犬')
d.sleep()  # 类方法: True
Dog.sleep()  # 类方法: True

d.swim()
Dog.swim()

五.类中的常用属性和方法

__name__
通过类名访问,获取类名字符串
不能通过对象访问,否则报错

__dict__
通过类名访问,获取指定类的信息【类方法,静态方法,成员方法】,返回的是一个字典
通过对象访问,获取的该对象的信息【所有的属性和值】,,返回的是一个字典

__bases__
通过类名访问,查看指定类的所有的父类【基类】
class Man:
    pass

class Boy(Man):
    # __init__(): 魔术方法
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 运算符重载(了解)
    # + 加法
    def __add__(self, other):
        # return self.age + other.age
        return Boy(self.name + other.name, self.age + other.age)


# 对象
b = Boy('易烊千玺', 19)
print(__name__)
print(Boy.__name__)  # Boy

print(b.__dict__)  # {'name': '易烊千玺', 'age': 19}
print(b.__module__)  # __main__ 所属模块
print(Boy.__module__)  # __main__  所属模块

print(b.__class__)  #  对象所属的类
print(Boy.__bases__)  # (,) 所有父类


b2 = Boy('王源', 18)  # 37
b3 = b + b2
print(b3.name, b3.age)  # 易烊千玺王源 37

六.单例设计模式

什么是设计模式

​ 经过已经总结好的解决问题的方案

​ 23种设计模式,比较常用的是单例设计模式,工厂设计模式,代理模式,装饰模式

什么是单例设计模式

​ 单个实例【对象】

​ 在程序运行的过程中,确保某一个类只能有一个实例【对象】,不管在哪个模块中获取对象,获取到的都是同一个对象

​ 单例设计模式的核心:一个类有且仅有一个实例,并且这个实例需要应用在整个工程中

实际应用:数据库连接池操作-----》应用程序中多处需要连接到数据库------》只需要创建一个连接池即可,避免资源的浪费

__new__():实例从无到有的过程【对象的创建过程】
# 单例模式: 让类只创建一个对象

class Person:

    # init: 初始化时调用
    def __init__(self, name):
        print('__init__:', name)
        self.name = name

    # 类属性
    instance = None

    # new: 创建对象时调用
    @classmethod
    def __new__(cls, *args, **kwargs):
        print('__new__')

        if cls.instance == None:
            print('-----新建对象-----')
            # 新建对象
            cls.instance = super().__new__(cls)

        return cls.instance


# 对象
p1 = Person('李四')
p2 = Person('王五')
p3 = Person('赵六')

print(p1 == p2)
print(p1 == p3)
print(p1.name, p2.name, p3.name)  # 赵六 赵六 赵六

你可能感兴趣的:(Python学习,多态,设计模式,python,封装,类)