python魔方

魔法方法总是被双下划线包围,例如__init__。

魔法方法的“魔力”体现在它们总能够在适当的时候被自动调用。
魔法方法的第一个参数应为cls(类方法) 或者self(实例方法)。

  • cls:代表一个类的名称
  • self:代表一个实例对象的名称
  1. 基本的魔法方法
    __ init__(self[, …])
    构造器,当一个实例被创建的时候调用的初始化方法
class Rectangle:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def getPeri(self):
        return (self.x + self.y) * 2
    def getArea(self):
        return self.x * self.y
rect = Rectangle(4, 5)
print(rect.getPeri())  # 18
print(rect.getArea())  # 20

__ new__(cls[, …])
__ new__ 是在一个对象实例化的时候所调用的第一个方法,在调用 init 初始化前,先调用__new__。
__ new__ 至少要有一个参数cls,代表要实例化的类,此参数在实例化时由 Python 解释器自动提供,后面的参数直接传递给__init__。
__ new__`对当前类进行了实例化,并将实例返回,传给__init__的self。但是,执行了__new__,并不一定会进入__init__,只有__new__返回了,当前类cls的实例,当前类的__init__才会进入。

class A(object):
    def __init__(self, value):
        print("into A __init__")
        self.value = value

    def __new__(cls, *args, **kwargs):
        print("into A __new__")
        print(cls)
        return object.__new__(cls)
class B(A):
    def __init__(self, value):
        print("into B __init__")
        self.value = value

    def __new__(cls, *args, **kwargs):
        print("into B __new__")
        print(cls)
        return super().__new__(cls, *args, **kwargs)
b = B(10)
# 结果:
# into B __new__
# <class '__main__.B'>
# into A __new__
# <class '__main__.B'>
# into B __init__     
class A(object):
    def __init__(self, value):
        print("into A __init__")
        self.value = value

    def __new__(cls, *args, **kwargs):
        print("into A __new__")
        print(cls)
        return object.__new__(cls)
class B(A):
    def __init__(self, value):
        print("into B __init__")
        self.value = value

    def __new__(cls, *args, **kwargs):
        print("into B __new__")
        print(cls)
        return super().__new__(A, *args, **kwargs)
b = B(10)

# 结果:
# into B __new__
# <class '__main__.B'>
# into A __new__
# <class '__main__.A'>                   

若__new__没有正确返回当前类cls的实例,那__init__是不会被调用的,即使是父类的实例也不行,将没有__init__被调用。
可利用__new__实现单例模式。

class Earth:
    pass
a = Earth()
print(id(a))  # 260728291456
b = Earth()
print(id(b))  # 260728291624
class Earth:
    __instance = None  

    def __new__(cls):
        if cls.__instance is None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance
a = Earth()
print(id(a))  # 512320401648
b = Earth()
print(id(b))  # 512320401648            

__new__方法主要是当你继承一些不可变的 class 时(比如int, str, tuple), 提供给你一个自定义这些类的实例化过程的途径。

class CapStr(str):
    def __new__(cls, string):
        string = string.upper()
        return str.__new__(cls, string)
a = CapStr("i love lsgogroup")
print(a)  # I LOVE LSGOGROUP

__ str__(self)
当你打印一个对象的时候,触发__str__
当你使用%s格式化的时候,触发__str__
str强转数据类型的时候,触发__str__

__ repr__(self)
__ repr__是__str__的备胎
有__str__的时候执行__str__,没有实现__str__的时候,执行__repr__
__repr(obj)内置函数对应的结果是__repr__的返回值
当你使用%r格式化的时候 触发__repr

class Cat:
    def __init__(self, new_name, new_age):
        self.name = new_name
        self.age = new_age
    def __str__(self):
        return "名字是:%s , 年龄是:%d" % (self.name, self.age)
    def __repr__(self):
        return "Cat:(%s,%d)" % (self.name, self.age)
    def eat(self):
        print("%s在吃鱼...." % self.name)
    def drink(self):
        print("%s在喝可乐..." % self.name)
    def introduce(self):
        print("名字是:%s, 年龄是:%d" % (self.name, self.age))
tom = Cat("汤姆", 30)
print(tom)  # 名字是:汤姆 , 年龄是:30
print(str(tom)) # 名字是:汤姆 , 年龄是:30
print(repr(tom))  # Cat:(汤姆,30)
tom.eat()  # 汤姆在吃鱼....
tom.introduce()  # 名字是:汤姆, 年龄是:30

__ str__(self) 的返回结果可读性强。也就是说,__ str__ 的意义是得到便于人们阅读的信息,就像下面的 ‘2019-10-11’ 一样。
__ repr__(self) 的返回结果应更准确。怎么说,__ repr__ 存在的目的在于调试,便于开发者使用。

import datetime
today = datetime.date.today()
print(str(today))  # 2019-10-11
print(repr(today))  # datetime.date(2019, 10, 11)
print('%s' %today)  # 2019-10-11
print('%r' %today)  # datetime.date(2019, 10, 11)
  1. 算术运算符
    类型工厂函数,指的是不通过类而是通过函数来创建对象。
    __add(self, other)__定义加法的行为:+
    __sub(self, other)__定义减法的行为:-
    __mul__(self, other)定义乘法的行为:*
    __truediv__(self, other)定义真除法的行为:/
    __floordiv__(self, other)定义整数除法的行为://
    __mod__(self, other) 定义取模算法的行为:%
    __divmod__(self, other)定义当被 divmod() 调用时的行为
    __divmod__(a, b)把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)
    __pow__(self, other[, module])定义当被 power() 调用或 ** 运算时的行为
    __lshift__(self, other)定义按位左移位的行为:<<
    __rshift__(self, other)定义按位右移位的行为:>>
    __and__(self, other)定义按位与操作的行为:&
    __xor__(self, other)定义按位异或操作的行为:^
    __or__(self, other)定义按位或操作的行为:|

  2. 反算术运算符
    反运算魔方方法,与算术运算符保持一一对应,不同之处就是反运算的魔法方法多了一个“r”。当文件左操作不支持相应的操作时被调用。
    __radd__(self, other)定义加法的行为:+
    __rsub__(self, other)定义减法的行为:-
    __rmul__(self, other)定义乘法的行为:*
    __rtruediv__(self, other)定义真除法的行为:/
    __rfloordiv__(self, other)定义整数除法的行为://
    __rmod__(self, other) 定义取模算法的行为:%
    __rdivmod__(self, other)定义当被 divmod() 调用时的行为
    __rpow__(self, other[, module])定义当被 power() 调用或 ** 运算时的行为
    __rlshift__(self, other)定义按位左移位的行为:<<
    __rrshift__(self, other)定义按位右移位的行为:>>
    __rand__(self, other)定义按位与操作的行为:&
    __rxor__(self, other)定义按位异或操作的行为:^
    __ror__(self, other)定义按位或操作的行为:|
    a + b这里加数是a,被加数是b,因此是a主动,反运算就是如果a对象的__add__()方法没有实现或者不支持相应的操作,那么 Python 就会调用b的__radd__()方法。

  3. 增量赋值运算符
    __iadd__(self, other)定义赋值加法的行为:+=
    __isub__(self, other)定义赋值减法的行为:-=
    __imul__(self, other)定义赋值乘法的行为:*=
    __itruediv__(self, other)定义赋值真除法的行为:/=
    __ifloordiv__(self, other)定义赋值整数除法的行为://=
    __imod__(self, other)定义赋值取模算法的行为:%=
    __ipow__(self, other[, modulo])定义赋值幂运算的行为:**=
    __ilshift__(self, other)定义赋值按位左移位的行为:<<=
    __irshift__(self, other)定义赋值按位右移位的行为:>>=
    __iand__(self, other)定义赋值按位与操作的行为:&=
    __ixor__(self, other)定义赋值按位异或操作的行为:^=
    __ior__(self, other)定义赋值按位或操作的行为:|=

  4. 一元运算符
    __neg__(self)定义正号的行为:+x
    __pos__(self)定义负号的行为:-x
    __abs__(self)定义当被abs()调用时的行为
    __invert__(self)定义按位求反的行为:~x

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西在路上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值