python基础之Day10 python是面向对象的语言(3)

特殊方法

python 的运算符实际上是通过调用对象的特殊方法实现的

运算符方法说明
运算符+__add__加法
运算符-__sub__减法
<,<=,==__lt__,__le__,__eq__比较运算符
>,>=,!=__gt__,__ge__,__ne__比较运算符
,^,&__or__,__xor__,__and__或、异或、与
<<,>>__lshift__,__rshift__左移、右移
*,/,%,//__mul__,__truediv__,__mod__,__floordiv__乘、浮点除、模运算(取余)、整数除
**__pow__指数运算
方法说明例子
__init__构造方法对象创建:p = Person()
__del__析构方法对象回收
__repr__,__str__打印,转换print(a)
__call__函数调用a()
__getattr__点号运算a.xxx
__setattr__属性赋a.xxx = value
__getitem__索引运算a[key]
__setitem__索引赋值a[key]=value
__len__长度len(a)

运算符重载

可以重写上面的特殊方法,即实现了“运算符的重载”

class Person:
    def __init__(self,name):
        self.name=name
    def __add__(self,other):
        if isinstance(other,Person):
            return '{}--{}'.format(self.name,other.name)
        else:
            print('they don\'t belong to the same class')
    def __mul__(self, other):
        return '{1} {0}s is {1} pigs.'.format(self.name,str(other))

p1=Person('yueyue')
p2=Person('guangguang')

p1+p2
#'yueyue--guangguang'

p3='shit'
p1+p3
#they don't belong to the same class

p1*3
#'3 yueyues is 3 pigs.'

特殊属性

Python 对象中包含了很多双下划线开始和结束的属性,这些是特殊属性,有特殊用法。

特殊方法含义
obj.__dict__对象的属性字典
obj.__class__对象所属的类
class.__bases__类的基类元组(多继承)
class.__base__类的基类
class.__mro__类层次结构
class.__subclasses__()子类列表

对象的浅拷贝和深拷贝

具体分析见:https://blog.csdn.net/little_yueyue/article/details/108210843

import copy
class Tshirt:
    def __init__(self,material,size):
        self.material=material
        self.size=size
class Material:
    def __init__(self):
        self.qualit='high-quality'
class Size:
    def __init__(self):
        self.size='mean'

m1=Material()
s1=Size()
T1=Tshirt(m1,s1)

#测试赋值
T2=T1
print(T1,T1.material,T1.size)
print(T2,T2.material,T2.size)
#<__main__.Tshirt object at 0x000001D61AE6AEC8> <__main__.Material object at 0x000001D61AE6E648> <__main__.Size object at 0x000001D61AE6EE48>
#<__main__.Tshirt object at 0x000001D61AE6AEC8> <__main__.Material object at 0x000001D61AE6E648> <__main__.Size object at 0x000001D61AE6EE48>

#测试浅拷贝
T3=copy.copy(T1)
print(T1,T1.material,T1.size)
print(T3,T3.material,T3.size)
#<__main__.Tshirt object at 0x000001D61AE6AEC8> <__main__.Material object at 0x000001D61AE6E648> <__main__.Size object at 0x000001D61AE6EE48>
#<__main__.Tshirt object at 0x000001D6195C84C8> <__main__.Material object at 0x000001D61AE6E648> <__main__.Size object at 0x000001D61AE6EE48>

#测试深拷贝
T4=copy.deepcopy(T1)
print(T1,T1.material,T1.size)
print(T4,T4.material,T4.size)
#<__main__.Tshirt object at 0x000001D61AE6AEC8> <__main__.Material object at 0x000001D61AE6E648> <__main__.Size object at 0x000001D61AE6EE48>
#<__main__.Tshirt object at 0x000001D61AF4ACC8> <__main__.Material object at 0x000001D61AF4A7C8> <__main__.Size object at 0x000001D61AF4AF48>

组合

关系说明例子
继承,“is-a”关系实现子类拥有的父类的方法和属性狗是动物
组合,“has-a” 关系实现一个类拥有另一个类的方法和属性手机拥有 CPU
#使用继承实现代码复用
class A:
    def say_name(self):
        print('A')
class B(A):pass

b1=B()
b1.say_name()
#A

#同样的效果,使用组合来实现代码的复用
class A:
    def say_name(self):
        print('A')
class B:
    def __init__(self,a):
        self.a=a
a=A()
b2=B(a)
b2.a.say_name()
#A

设计模式

工厂模式

工厂模式实现了创建者和调用者的分离, 使用专门的工厂类将选择实现类、 创建对象进行统一的管理和控制。

class School:
    def construction_discipline(self,discipline):
        if discipline=='数学':
            return Math()
        elif discipline=='统计':
            return Statistic()
        else:
            print('unknown discipline')
class Math:
    pass
class Statistic:
    pass

school=School()
d1=Math()  #之前创建Math的方式
d2=school.construction_discipline('数学')  #现在创建的方式

单例模式

单例模式的核心作用是确保一个类只有一个实例,并且提供一个访问该实例的全局访问点
要重写__new__,__init__方法

class School:
    __obj=None
    __init_flag=True
    
    def __init__(self,name):
        if School.__init_flag:
            self.name=name
            print('{} is building...'.format(self.name))
            School.__init_flag=False
        else:
            print('you have built a school.')
    def __new__(cls,*args,**kwargs):
        if cls.__obj==None:
            cls.__obj=object.__new__(cls)
        return cls.__obj

s1=School("yueyue\'s school")
s2=School("hope school")
#yueyue's school is building...
#you have built a school.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值