Python Data Class Slots
我们分别跑一下这2个类:
2种方法初始内存略有差别,但是由于这个差别和总内存量相比太小而忽略不计,结论就是:
使用slots可以让内存使用减少3.5倍!!# 通过 (200 - 4) / ((60 - 4) * 1.0) 计算得来
那么用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
第三点有点难理解,我写个例子看看吧:
Slot Machine In Python
所以实例不超过万级别的类,__slots__是不太值得使用的。
PS:《fluent python》比我狠,说的是小于百万级别实例不值得使用。
无耻的广告:《Python Web开发实战》上市了!
Python Data Class Slots Games
欢迎关注本人的微信公众号获取更多Python相关的内容(也可以直接搜索「Python之美」):