一些内置的魔术方法

_call_ : 对象() 调用这一类中的__call__方法

class A:
    def __call__(self, *args, **kwargs):
        print('_________')
obj = A()
print(callable(obj))
obj()
A()() #obj = A() ==>obj()
 __len__  : len(对象) 必须完成这一,类里加__len__方法
class Cls:
    def __init__(self,name):
        self.name = name
        self.students = []
    def len(self):
        return len(self.students)
    def __len__(self):
        return len(self.students)
py22 = Cls('py22期')
py22.students.append('大壮')
py22.students.append('alex')
print(py22.len())
print(len(py22))

---------------------
class Pow:
    def __init__(self,n):
        self.n = n
    def __pow2__(self):
        return self.n ** 2

def pow2(obj):
    return obj.__pow2__()

obj = Pow(10)
print(pow2(obj))

__new:

实例化的情况下

先建立一块对象的室内空间,有一个表针能偏向类 --> new

调用init --> init

class A:
    def __new__(cls, *args, **kwargs):
        o = object.__new__(cls)
        print('实行new',o)
        return o
    def __init__(self):
        print('实行init',self)
A() 
# 实行new <__main__.A object at 0x00000000022802C8>
# 实行init <__main__.A object at 0x00000000022802C8>

策略模式 -- 单例模式

# 一个类 从头至尾 总是建立一次self的室内空间
class Baby:
    __instance = None  #标志
    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance
    def __init__(self,cloth,pants):
        self.cloth = cloth
        self.pants = pants
b1 = Baby('红毛衣','绿皮裤')
print(b1.cloth)  #红毛衣
b2 = Baby('白衬衣','黑豹纹')
print(b1.cloth)  #白衬衣
print(b2.cloth)  #白衬衣

_str_:协助我们在复印\展现对象的情况下更形象化的显示信息对象內容 %s str() print()

_repr_:repr是str的备用胎,另外还和%r和repr有合作关系

class clas:
    def __init__(self):
        self.student = []
    def append(self,name):
        self.student.append(name)
    def __str__(self):
        return str(self.student)
#
py22 = clas()
py22.append('大壮')
print(py22)
print(str(py22))
print('大家py22班 %s'%py22)
print(py22)
py22.append('大壮')
print(py22)
# ['大壮']
# ['大壮']
# 大家py22班 ['大壮']
# ['大壮']
# ['大壮', '大壮']
# 在复印一个对象的情况下 调用__str__方法
# 在%s拼凑一个对象的情况下 调用__str__方法
# 在str一个对象的情况下 调用__str__方法
class clas:
    def __init__(self):
        self.student = []
    def append(self,name):
        self.student.append(name)
    def __repr__(self):
        return str(self.student)
    def __str__(self):
        return 'aaa'

py22 = clas()
py22.append('大壮')
print(py22)
print(str(py22))
print('大家py22班 %s'%py22)
print('大家py22班 %r'%py22)
print(repr(py22))
# aaa
# aaa
# 大家py22班 aaa
# 大家py22班 ['大壮']
# ['大壮']

# 在我们复印一个对象 用%s开展字符串拼接 或是str(对象)一直调用这一对象的__str__方法
# 假如找不着__str__,就调用__repr__方法
# __repr__不但是__str__的代替品,也有自身的作用
# 用%r开展字符串拼接 或是用repr(对象)的情况下一直调用这一对象的__repr__方法
本文版权归去快排wWw.seogUrublog.com 所有,如有转发请注明来出,竞价开户托管,seo优化请联系qq❉61910465