刻意练习Python基础 ——day 15:魔法方法(上)

17天 —— Python基础刻意练习

Day 01——Task01:变量、运算符与数据类型
Day 02——Task02:条件与循环
Day 03——Task03:列表与元组(上)
Day 04——Task03:列表与元组(下)
Day 05——Task04:字符串与序列
Day 06——Task05:函数与Lambda表达式(上)
Day 07——Task05:函数与Lambda表达式(下)
Day 08——Task06:字典与集合
Day 09——Task07:文件与文件系统(上)
Day 10——Task07:文件与文件系统(下)
Day 11——Task08:异常处理
Day 12——Task09:else 与 with 语句
Day 13——Task10:类与对象(上)
Day 14——Task10:类与对象(下)
Day 15——Task11:魔法方法(上)
Day 16——Task11:魔法方法(下)
Day 17——Task12:模块
    



魔法方法



1. 基础语法

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

  魔法方法是面向对象的 Python 的一切,如果你不知道魔法方法,说明你还没能意识到面向对象的 Python 的强大。

  魔法方法的“魔力”体现在它们总能够在适当的时候被自动调用。

  魔法方法的第一个参数应为cls(类方法) 或者self(实例方法)。

  • cls:代表一个类的名称

  • self:代表一个实例对象的名称






2.魔法方法


 2.1. 基本的魔法方法


  2.1.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



  2.1.2 __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)  # 改动了cls变为A


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



  2.1.3 __del__(self)

  • 析构器,当一个对象将要被系统回收之时调用的方法。

Python 采用自动引用计数(ARC)方式来回收对象所占用的空间,当程序中有一个变量引用该 Python 对象时,Python 会自动保证该对象引用计数为 1;当程序中有两个变量引用该 Python 对象时,Python 会自动保证该对象引用计数为 2,依此类推,如果一个对象的引用计数变成了 0,则说明程序中不再有变量引用该对象,表明程序不再需要该对象,因此 Python 就会回收该对象。
大部分时候,Python 的 ARC 都能准确、高效地回收系统中的每个对象。但如果系统中出现循环引用的情况,比如对象 a 持有一个实例变量引用对象 b,而对象 b 又持有一个实例变量引用对象 a,此时两个对象的引用计数都是 1,而实际上程序已经不再有变量引用它们,系统应该回收它们,此时 Python 的垃圾回收器就可能没那么快,要等专门的循环垃圾回收器(Cyclic Garbage Collector)来检测并回收这种引用循环。

class C(object):
    def __init__(self):
        print('into C __init__')

    def __del__(self):
        print('into C __del__')


c1 = C()
# into C __init__
c2 = c1
c3 = c2
del c3
del c2
del c1
# into C __del__



  2.1.4 __str__ 和 __repr__

  __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)




 2.2. 算术运算符

  • 类型工厂函数,指的是不通过类而是通过函数来创建对象。
class C:
    pass


print(type(len))  # <class 'builtin_function_or_method'>
print(type(dir))  # <class 'builtin_function_or_method'>
print(type(int))  # <class 'type'>
print(type(list))  # <class 'type'>
print(type(tuple))  # <class 'type'>
print(type(C))  # <class 'type'>
print(int('123'))  # 123

# 这个例子中list工厂函数把一个元祖对象加工成了一个列表对象。
print(list((1, 2, 3)))  # [1, 2, 3]



  2.2.1.__add____sub__

  • __add__(self, other)定义加法的行为:+
  • __sub__(self, other)定义减法的行为:-
class MyClass:

    def __init__(self, height, weight):
        self.height = height
        self.weight = weight

    # 两个对象的长相加,宽不变.返回一个新的类
    def __add__(self, others):
        return MyClass(self.height + others.height, self.weight + others.weight)

    # 两个对象的宽相减,长不变.返回一个新的类
    def __sub__(self, others):
        return MyClass(self.height - others.height, self.weight - others.weight)

    # 说一下自己的参数
    def intro(self):
        print("高为", self.height, " 重为", self.weight)


def main():
    a = MyClass(height=10, weight=5)
    a.intro()

    b = MyClass(height=20, weight=10)
    b.intro()

    c = b - a
    c.intro()

    d = a + b
    d.intro()


if __name__ == '__main__':
    main()

# 高为 10  重为 5
# 高为 20  重为 10
# 高为 10  重为 5
# 高为 30  重为 15



  2.2.2. 其他的操作符

魔法方法 含义
__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.3. 反算术运算符

  • 反运算魔方方法,与算术运算符保持一一对应,不同之处就是反运算的魔法方法多了一个“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__()方法。

class Nint(int):
    def __radd__(self, other):
        return int.__sub__(other, self) # 注意 self 在后面


a = Nint(5)
b = Nint(3)
print(a + b)  # 8
print(1 + b)  # -2



 2.4. 增量赋值运算符

魔法方法 含义
__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) 定义赋值按位或操作的行为:|=



 2.5. 一元运算符

魔法方法 含义
__neg__(self) 定义正号的行为:+x
__pos__(self) 定义负号的行为:-x
__abs__(self) 定义当被abs()调用时的行为
__invert__(self) 定义按位求反的行为:~x






参考资料

  • https://blog.csdn.net/LSGO_MYP/article/details/102887712
  • https://www.runoob.com/python3/python3-tutorial.html
  • https://www.bilibili.com/video/av4050443
  • http://c.biancheng.net/view/2371.html
  • https://www.cnblogs.com/seablog/p/7173107.html
  • https://www.cnblogs.com/Jimmy1988/p/6804095.html
  • https://blog.csdn.net/johnsonguo/article/details/585193
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章