Python中魔法方法(__init__、__del__、__str__、__repr__、__call__、__eq__等)

一、魔法方法特点

  1. 不需要手动调用,会在合适的时机自动调用
  2. 这些方法,都是使用 __ 开始,使用 __ 结束
  3. 方法名都是系统规定好的,在合适的时机自己调用

二、__init__方法

class Student(object):
    def __init__(self, name, age):  # 重写了__init__方法
        self.name = name
        self.age = age

    def say_word(self):
        print(f'我叫{self.name}')


s1 = Student('lucy', 18)
print(s1.name)

总结:

  1. __init__()方法在创建对象时,会默认被调用,不需要手动的调用这个方法。
  2. __init__()方法里的self参数,在创建对象时不需要传递参数,python解释器会把创建好的对象引用直接赋值给self
  3. 在类的内部,可以使用self来使用属性和调用方法;在类的外部,需要使用对象名来使用属性和调用方法。
  4. 如果有多个对象,每个对象的属性是各自保存的,都有各自独立的地址。
  5. 方法是所有对象共享的,只占用一份内存空间,方法被调用时会通过self来判断是哪个对象调用了实例方法。

三、__del__方法

class Student(object):
    def __init__(self, name, age):  # 重写了__init__方法
        self.name = name
        self.age = age

    def __del__(self):
        # 当对象被销毁时,会自动调用这个方法
        print('__del__ 方法被调用了')


s1 = Student('lucy', 18)

总结:当删除对象时,python解释器会默认调用__del__()方法。

四、__str__方法

  1. 打印对象时,会调用对象的 __str__ 方法,默认会打印类名和对象的地址名
class Student(object):
    def __init__(self, name, age):  # 重写了__init__方法
        self.name = name
        self.age = age


s1 = Student('lucy', 18)
# 打印对象时,会调用对象的 __str__ 方法,默认会打印类名和对象的地址名
print(s1)  # <__main__.Student object at 0x000002082C731D48>
  1. 一般情况下,打印一个对象时,可能需要列出这个对象的所有属性,可以重写 __str__ 方法。
class Student(object):
    def __init__(self, name, age):  # 重写了__init__方法
        self.name = name
        self.age = age

    def __str__(self):
        return f'姓名:{self.name},年龄:{self.age}'


s1 = Student('lucy', 18)
print(s1)  # 姓名:lucy,年龄:18

五、__repr__方法

  1. __repr__方法和__str__方法功能类似,都是用来修改一个对象的默认打印内容。在打印一个对象时,如果没有重写__str__方法,它会自动来查找__repr__方法。如果这两个方法都没有,会直接打印这个对象的内存地址。如果两个方法都写了,选择 __str__方法。
class Student(object):
    def __init__(self, name, age):  # 重写了__init__方法
        self.name = name
        self.age = age

    # def __str__(self):
    #     return f'姓名:{self.name},年龄:{self.age}'

    def __repr__(self):
        return f'姓名:{self.name},年龄:{self.age}'


s1 = Student('lucy', 18)
print(s1)  # 姓名:lucy,年龄:18

六、__call__方法

  1. 对象名() ,其实就是调用这个对象的 对象名.__call__() 方法。
class Student(object):
    def __init__(self):
        pass

    def __call__(self, *args, **kwargs):
        print('args={},kwargs={}'.format(args, kwargs))


s1 = Student()
s1(1, 2, 4, 5, m='good', n='hehehe', p='heiheihei')  # args=(1, 2, 4, 5),kwargs={'m': 'good', 'n': 'hehehe', 'p': 'heiheihei'}

七、__eq__方法

  1. __eq__ 方法如果不重写,默认比较依然是内存地址
class Student(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        return self.name == other.name and self.age == other.age


s1 = Student('lucy', 18)
s2 = Student('lucy', 18)
s3 = Student('lucy', 20)

# s1 == s2本质是调用 p1.__eq__(p2),获取这个方法的返回结果
print(s1 == s2)  # True 
print(s1 == s3)  # False

注意:== 会调用对象的 __eq__ 方法,获取这个方法的比较结果

  1. is比较的是内存地址
print(id(s1) is id(s2))  # False
  1. 相关习题
nums1 = [1, 2, 3]
nums2 = [1, 2, 3]
print(nums1 is nums2)  # False
print(nums1 == nums2)  # True

八、比较运算符相关魔法方法

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):  # 等于
        return self.name == other.name and self.age == other.age

    def __ne__(self, other):  # 不等于
        return self.age != other.age

    def __lt__(self, other):  # 小于
        return self.age < other.age
        # return self.age < other

    def __gt__(self, other):  # 大于
        return self.age > other.age

    def __le__(self, other):  # 小于等于
        return self.age <= other.age

    def __ge__(self, other):  # 大于等于
        return self.age >= other.age


s1 = Student('zhangsan', 18)
s2 = Student('zhangsan', 18)
s3 = Student('lisi', 20)
print(s1 == s2)  # True
print(s1 != s2)  # False
print(s1 < s2)  # False
# print(s1 < 6)  # False
print(s1 > s2)  # False
print(s1 <= s2)  # True
print(s1 >= s2)  # True

九、算数运算符相关魔法方法

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __add__(self, other):
        return self.age + other

    def __sub__(self, other):
        return self.age - other

    def __mul__(self, other):
        return self.age * other

    def __truediv__(self, other):
        return self.age / other

    def __mod__(self, other):
        return self.age % other

    def __pow__(self, power, modulo=None):
        return self.age ** power


s = Student('zhangsan', 18)
print(s + 1)  # 19
print(s - 2)  # 16
print(s * 2)  # 36
print(s / 5)  # 3.6
print(s % 5)  # 3
print(s ** 2)  # 324

十、类型转换相关魔法方法

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __int__(self):
        return self.age

    def __float__(self):
        return self.age * 1.0

    def __str__(self):
        return self.name

    def __bool__(self):
        return self.age > 18


s = Student('zhangsan', 18)
print(int(s))  # 18
print(float(s))  # 18.0
print(str(s))  # zhangsan
print(bool(s))  # False

发布了31 篇原创文章 · 获赞 48 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/mall_lucy/article/details/104489036