Python Data Class Slots

Python Data Class Slots 9,1/10 7136 reviews
  1. Python Slots Vs Data Class
  2. Slot Machine In Python
  3. Python Data Class Slots Games
Python老鸟都应该看过那篇非常有吸引力的 Saving 9 GB of RAM with Python’s __slots__ 文章,作者使用了__slots__让内存占用从25.5GB降到了16.2GB。在当时来说,这相当于用一个非常简单的方式就降低了30%的内存使用,着实惊人。作者并没有提到他的业务特点和代码,那我们就基于《fluent python》中的例子来验证下是不是有这么厉害:

我们分别跑一下这2个类:

2种方法初始内存略有差别,但是由于这个差别和总内存量相比太小而忽略不计,结论就是:

使用slots可以让内存使用减少3.5倍!!# 通过 (200 - 4) / ((60 - 4) * 1.0) 计算得来
Python class data member

那么用slot就是非非常那个有必要吗?事实上500000个实例这种机会非常少见,用不用完全根据业务来决定,并不要以偏概全。因为(敲黑板了哈)使用__slots__也是有副作用的:

In this particular example, the slot class is about 35% faster. Conclusion & Further Reading. Data classes are one of the new features of Python 3.7. With data classes, you do not have to write boilerplate code to get proper initialization, representation, and comparisons for your objects. You have seen how to define your own data classes, as. The docstrings for classes should summarize its behavior and list the public methods and instance variables. The subclasses, constructors, and methods should each have their own docstrings. Example 6: Docstrings for Python class. Suppose we have a Person.py file with the following code: class Person: ' A class to represent a person. The dataclasses is a new module added in Python's standard library since version 3.7. It defines @dataclass decorator that automatically generates constructor magic method init , string representation method repr , the eq method which overloads operator (and a few more) for a user defined class.

Python Slots Vs Data Class

第三点有点难理解,我写个例子看看吧:

Python slot machine code

Slot Machine In Python

Python data class slots games

所以实例不超过万级别的类,__slots__是不太值得使用的。

PS:《fluent python》比我狠,说的是小于百万级别实例不值得使用。

无耻的广告:《Python Web开发实战》上市了!

PythonClass

Python Data Class Slots Games

欢迎关注本人的微信公众号获取更多Python相关的内容(也可以直接搜索「Python之美」):