5.魔术方法-2

魔术方法第二部分

1. __str__魔术方法

# 1.__str__魔术方法
"""
触发时机 : 使用print(对象)打印对象或者str(对象)强转对象时触发
功能 : 查看对象
参数 : 一个self就收当前对象
返回值 : 必须返回字符串类型
"""
class Cat():
    gift = "好奇心"
    def __init__(self,name):    
        self.name = name
    def info(self):
        return "猫的名字叫{},天赋{}".format(self.name,self.gift)
    def __str__(self):
        return self.info()
        
tom = Cat("tom")
print(tom) #打印对象触发
res = str(tom) #强转str类型触发
print(res)

2. __repr__魔术方法

# 2.__repr__魔术方法
"""
触发时机 : 使用repr(对象)的时候触发
功能 : 查看对象 ,与__str__相似
参数 : 一个self就收当前对象
返回值 : 必须返回字符串类型
"""

class Mouse():
    gift = "打洞"
    def __init__(self,name):
        self.name = name
    def info(self):
        return "我是{},我喜欢{}".format(self.name,self.gift)
    def __repr__(self):
        return self.info()

jerry = Mouse("jerry")
res = repr(jerry)
print(res)
"""
在print(对象)或者str强转对象时,依旧触发__repr__
原因是 : 系统在底层加入了如下语句
    __str__ = __repr__
"""
print(jerry)
res = str(jerry)
print(res)

3. bool魔术方法

# 3.__bool__魔术方法
"""
触发时机 : 使用bool(对象)的时候触发
功能 : 强转对象
参数 : 一个self就收当前对象
返回值 :必须是布尔类型
"""
class Bo():
    def __bool__(self):
        return False
obj = Bo()
res = bool(obj) #强转对象时触发
print(res) #False

"""
类似的魔术方法还有如下等等:
__complex__(self) 使用complex(对象)时触发,返回值必须是虚数
__int__(self)           使用int(对象)时触发,返回值必须是整数
__float__(self)        使用float(对象)时触发,返回值必须是浮点数
    ...
"""

4. add (radd) 魔术方法

# 4.__add__魔术方法(__radd__反向加法)
"""
触发时机 : 使用对象进行加法运算时自动触发
功能 : 对象加法运算
参数 : 两个对象参数(self,other)
返回值 : 运算后的结果
"""
class Jia():
    def __init__(self,num):
        self.num = num
    def __add__(self,num):
        return self.num + num
    def __radd__(self,num):
        return num + self.num

obj = Jia(5)
# 对象在加号左边,自动触发__add__魔术方法
res = obj +5
print(res) #10
# 对象在加号右边,自动触发__radd__魔术方法
res = 3 + obj
print(res) #8

"""
类似的魔术方法还有如下等等:(都需要两个参数)
__sub__(__rsub__)       定义减法(subtraction)的行为: -
__mul__(__rmul__)      定义乘法(multiplication)的行为: *
__truediv__(__rtruediv__) 定义真除法的行为 : /
"""
class Chu():
    def __init__(self,num):
        self.num = num
    def __truediv__(self,num):
        return (self.num / num) if num != 0 else "0不能做除数"
    def __rtruediv__(self,num):
        return (num / self.num) if self.num != 0 else "0不能做除数"

obj = Chu(10)
res = obj / 4
print(res) #2.5
res = obj / 0
print(res) #0不能做除数
obj = Chu(0)
res = 10 / obj
print(res) #0不能做除数

5. len 魔术方法

# 5.__len__魔术方法
"""
触发时机 : 使用len(对象)的时候触发
功能 : 用于检测对象中或类中成员个数
参数 : 一个self就收当前对象
返回值 : 必须是整数
"""
# 检测对象中成员个数
class Me():
    a = 1
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def func(self):
        pass
    def __len__(self):
        return len(self.__dict__)

obj = Me("tom",3)
res = len(obj) #触发魔术方法
print(res) #2
obj.sex = "男"
res = len(obj)
print(res) #3

# 检测类中成员个数
class My():
    a = 1
    __b = 2
    def func(self):
        pass
    def __info(self):
        pass
    def __len__(self):
        lst = []
        dic = My.__dict__
        for i in dic:
            # 筛选掉类中的魔术属性
            if not(i.startswith("__") and i.endswith("__")):
                lst.append(i)
        return len(lst)
"""
魔术方法里面可以简写成推导式: 
    return len([i for i in My.dict if not(i.starswith("__") and i.endswith("__"))])
"""
obj = My()
res = len(obj) 
print(res) #4

原文地址:https://www.cnblogs.com/jia-shu/p/14157255.html