魔法方法

    技术2023-11-05  107

    构造和析构

    init(self [, …]):初始化需求下,需要重写,本身也是自带的有。根据具体的类的需要进行设计,init()是没有返回值的

    new(cls[, …]): cls为这个类的本身,一般情况下不重写。为当前类添加运行前的一个方法.

    class CapStr(str): def __new__(cls, string): string = string.upper() return str.__new__(cls, string) a = CapStr('i Love Fishc.com') del(self): 析构器, 当一个对象没有指向的时候,就会调用,例如下面,只有当3个标签全部没有的时候,才会调用__init__() >>> class C: def __init__(self): print("__Init__()被调用了!") def __del__(self): print("__del__()被调用了!") >>> c1 = C() __Init__()被调用了! >>> c2 = c1 >>> c3 = c2 >>> del c1 >>> del c3 >>> del c2 __del__()被调用了!

    算术运算1

    工厂函数: 工厂函数是指这些内建函数都是类对象, 当调用它们时,实际上是创建了一个类实例;如下面的例子中,实现加法的时候,自动调用的是魔法方法,因此我们可以重新定义魔法方法; 利用python函数输出可以是函数的功能,将某些参数传入,输出一个封装好的针对专门用户的函数,更方便用户使用。调用内置函数,实际上是创建实例化对象; class New_int(int): def __add__(self, other): return int.__sub__(self, other) def __sub__(self, other): return int.__add__(self, other) a = New_int(3) b = New_int(5) print(a + b) print(a - b) '''结果是 -2, 和 8 '''

    算数运算2

    魔法方法:https://fishc.com.cn/thread-48793-1-2.html

    a + b,加法用的是a的魔法方法,如果右操作数的类型是左操作数的子类,并且该子类提供了操作的逆方法,那么优先调用逆方法。 class Nint(int): def __radd__(self, other): return int.__sub__(self, other) a = Nint(5) b = Nint(3) print(a + b) print(1 + b) # 结果是2,因为1是int类的对象, # 而b是继承而来的Nint的对象,所以优先运行b的逆方法 # 此时self指的是b,other指的是1 # 重写反运算,注意顺序问题 属性访问举例

    描述符

    将某种特殊类型的类的实例指派给另一个类的属性,

    property就是一个描述符类 class MyProperty: def __init__(self, fget=None, fset=None, fdel=None): self.fget = fget self.fset = fset self.fdel = fdel def __get__(self, instance, owner): return self.fget(instance) def __set__(self, instance, value): self.fset(instance, value) def __delete__(self, instance): self.fdel(instance) class C: def __init__(self): self.__x = None def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = MyProperty(getx, setx, delx) c = C()

    定制序列

    class Countlist: def __init__(self, *args): self.values = [x for x in args] self.count = {}.fromkeys(range(len(self.values)), 0) def __len__(self): return len(self.values) def __getitem__(self, key): self.count[key] += 1 return self.values[key] c1 = Countlist(1, 3, 5, 7, 9) c2 = Countlist(2, 4, 6, 8, 10) >>> c1[1] 3 >>> c1[1] 3 >>> c1[1] 3 >>> c1.values[1] 3 >>> c1.count {0: 0, 1: 3, 2: 0, 3: 0, 4: 0}
    Processed: 0.014, SQL: 9