文章目录
一、如何派生内置不可变类型并修改其实例行为
1.1 练习需求
我们想自定义一种新类型的元组,对于传入的可迭代对象,我们只保留其中int类型且值大于0的元素需求,定义IntTuple类
>>> IntTuple([2,-2,"jr",["x","y"],4])
(2,4)
class Demo(object):
def __new__(cls, *args, **kwargs):
print("__new__")
def __init__(self):
print("__init__")
d = Demo()
1.**new**方法是创建对象的方法
- 1.此处重写了父类的方法
- 2.需调用父类的**new**方法创建对象
- 3.需将对象返回出来给**init**方法
2.**init**方法为初始化方法
- 注意:当创建完对象时,自动调用它
class Demo(object):
def __new__(cls, *args, **kwargs):
print("__new__")
return object.__new__(cls)
#return super().__new__(cls)
def __init__(self):
print("__init__")
d = Demo()
1.2练习实现
class IntTuple(tuple):
def __new__(cls, iterable ):
f = [i for i in iterable if isinstance(i,int) and i>0]
return super().__new__(cls,f)
int_t = IntTuple([2,-2,"jr",["x","y"],4])
print(int_t) # (2, 4)
二、如何为创建大量实例节省内存
2.1练习需求
在游戏开发中,有一个玩家类Player,每有一个在线玩家,在服务器内则有一个player的实例,当在线的人数很多时,将产生大量实例(百万级)
如何降低这些大量实例的内存开销?
解决方案:定义类的 __slots__
属性,声明实例有哪些属性(关闭动态绑定)
class Player