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']

 

posted on 2018-05-08 15:08  石中玉smulngy  阅读(141)  评论(0编辑  收藏  举报

导航