Python之__slots__ &运算符重载反向运算

1.运算符重载之反向运算

class A:
    def __init__(self,x):
        self.x = x

    def __add__(self, other):
        try:
            x = other.x
            return self.x + other.x
        except AttributeError:
            try:
                x = int(other)
            except:
                x = 0
            return A(self.x + x)

    def __iadd__(self, other):
        print(self,'iadd')
        return A(self.x + other.x)

    def __radd__(self, other):
        print(self,'radd')
        return self.x + other.x
    def __repr__(self):
        return '{}'.format(self.x)
#a + 1  ;;; 1+a
a = A(4)
b = A(5)
print("-----------end----------------")
print((a+'abc').x) # a.__add__(1) 1时int没有self.x属性 抛出异常

'''
1+a 等价于
1.__add__(a) int也实现了__add__方法 ,这个方法对这种的加法返回值时notimplement
解释器发现这个值就会发起对第二个参数a的__radd__方法
'''
'''
__add__ 第一个try语句解决了 传入的 1是int类型没有x属性报属性异常,
第二个try 是解决传入的字符串问题,如果传人字符串设置x = 0 不抛出异常
'''

2.__slots__问题引出、

1.字典为提升查询效率必须用空间换时间
2.一般来说一个对象,属性多一i但,都存储在字典中便于查询
3.但是如果数百万个对象,那么字典占得就很大了
4.考虑把属性字典__dict__省了
5.提供__slots__

__slots__告诉解释器,实例的的属性都叫什么,一般来说既然节省内存,还是使用元祖比较好
一旦类提供了__slots__,就组织了实例产生__dict__来保存实例
也不可以动态增加属性
不影响子类实例,不会继承下去,除非子类也自己定义了__slots__

应用场景
使用构建在数百万上的对象,且容量较为紧张,实例的属性简单,固定且不用增加动态场景

 

class A:
    x = 1
    __slots__ = ('z','y')
    def __init__(self):
        self.y = 6
        self.z = 7

猜你喜欢

转载自www.cnblogs.com/harden13/p/9063384.html