Python Magic_Methods 魔法方法

# 无论输入任意key,都不会出错,并且value的值不会发生改变
# 数学对象两个必须一样
class TestMagic(object):
    def __init__(self,num):
        self.a = num

    def __setitem__(self, key, value):
        self.a = value

    def __getitem__(self, item):
        return self.a

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

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

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

t = TestMagic(10)
t['123as6d'] = 5   # t.__setitem__('123as6d', 10)
print(t['dasdqwd'])  #  t.__getitem__('dasdqwd')

a = TestMagic(20)
b = TestMagic(30)

print(TestMagic(20) * TestMagic(30))
print(a+b) # a.__add__(b)

猜你喜欢

转载自blog.csdn.net/weixin_42785547/article/details/85089147