您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python中的__SLOTS__属性使用示例

2024/3/14 20:43:12发布29次查看
看python社区大妈组织的内容里边有一篇讲python内存优化的,用到了__slots__。然后查了一下,总结一下。感觉非常有用
python类在进行实例化的时候,会有一个__dict__属性,里边有可用的实例属性名和值。声明__slots__后,实例就只会含有__slots__里有的属性名。
# coding: utf-8 class a(object): x = 1 def __init__(self): self.y = 2 a = a()print a.__dict__print(a.x, a.y)a.x = 10a.y = 10print(a.x, a.y) class b(object): __slots__ = ('x', 'y') x = 1 z = 2 def __init__(self): self.y = 3 # self.m = 5 # 这个是不成功的 b = b()# print(b.__dict__)print(b.x, b.z, b.y)# b.x = 10# b.z = 10b.y = 10print(b.y) class c(object): __slots__ = ('x', 'z') x = 1 def __setattr__(self, name, val): if name in c.__slots__: object.__setattr__(self, name, val) def __getattr__(self, name): return value of %s % name c = c()print(c.__dict__)print(c.x)print(c.y)# c.x = 10c.z = 10c.y = 10print(c.z, c.y)c.z = 100print(c.z)
{'y': 2}(1, 2)(10, 10)(1, 2, 3)10value of __dict__1value of y(10, 'value of y')100
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product