7-2 如何为创建大量实例节省内存

 

1、创建一个模块,定义两个类playerplayer2,执行完后,可以直接导入

>>> p1 = player('0001','Jim')
>>> p2 = player2('0001','Jim')

创建两个对象p1和p2,其中p1要比p2大

 

2、查看p1和p2的属性

>>> help(dir)
Help on built-in function dir in module __builtin__:

dir(...)
    dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.
help(dir)
>>> dir(p1)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'level', 'name', 'stat', 'uid']

>>> dir(p2)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'level', 'name', 'stat', 'uid']
>>> set(dir(p1)) - set(dir(p2))   #将其发生转为集合后,再执行差集
set(['__dict__', '__weakref__'])  #多了两个属性,在不使用弱引用时,__weakref__属性很小,忽略不计,责任落在了__dict__属性上
>>> 

3、__dict__是一个字典,实例动态属性绑定的字典

>>> p1.__dict__
{'stat': 0, 'level': 1, 'uid': '0001', 'name': 'Jim'}

4、动态属性绑定,比如p1没有x属性,可以直接给这个属性赋值,从而创建了这个属性

>>> p1.x

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    p1.x
AttributeError: 'player' object has no attribute 'x'
>>> p1.x = 123
>>> p1.x
123
>>> p1.__dict__
{'x': 123, 'stat': 0, 'level': 1, 'uid': '0001', 'name': 'Jim'}

>>> p1.__dict__['y'] = 99
>>> p1.y
99

5、动态解除属性

>>> del p1.__dict__['x']
>>> p1.__dict__
{'stat': 0, 'uid': '0001', 'level': 1, 'y': 99, 'name': 'Jim'}

6、查看占用内存情况

>>> import sys
>>> sys.getsizeof(p1.__dict__)
524

7、__slots__属性提前定义好了属性,不会再变,没有了__dict__属性,也就没有了动态绑定功能,类似于C语言的结构体

 

__slots__ = ['uid', 'name', 'stat', 'level']

 

转载于:https://www.cnblogs.com/smulngy/p/9008306.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值