我们分别跑一下这2个类:
When called into existence, the dict attribute is a minimum of 280 bytes additionally. In contrast, a class instance with slots declared to be (no data) is only 16 bytes, and 56 total bytes with one item in slots, 64 with two.
2种方法初始内存略有差别,但是由于这个差别和总内存量相比太小而忽略不计,结论就是:
使用slots可以让内存使用减少3.5倍!!# 通过 (200 - 4) / ((60 - 4) * 1.0) 计算得来
那么用slot就是非非常那个有必要吗?事实上500000个实例这种机会非常少见,用不用完全根据业务来决定,并不要以偏概全。因为(敲黑板了哈)使用__slots__也是有副作用的:
第三点有点难理解,我写个例子看看吧:
所以实例不超过万级别的类,__slots__是不太值得使用的。
PS:《fluent python》比我狠,说的是小于百万级别实例不值得使用。
无耻的广告:《Python Web开发实战》上市了!
欢迎关注本人的微信公众号获取更多Python相关的内容(也可以直接搜索「Python之美」):
This page describes the use of signals and slots in Qt for Python.The emphasis is on illustrating the use of so-called new-style signals and slots, although the traditional syntax is also given as a reference.
The main goal of this new-style is to provide a more Pythonic syntax to Python programmers.
QtCore.SIGNAL() and QtCore.SLOT() macros allow Python to interface with Qt signal and slot delivery mechanisms.This is the old way of using signals and slots.
The example below uses the well known clicked signal from a QPushButton.The connect method has a non python-friendly syntax.It is necessary to inform the object, its signal (via macro) and a slot to be connected to.
The new-style uses a different syntax to create and to connect signals and slots.The previous example could be rewritten as:
Signals can be defined using the QtCore.Signal() class.Python types and C types can be passed as parameters to it.If you need to overload it just pass the types as tuples or lists.
In addition to that, it can receive also a named argument name that defines the signal name.If nothing is passed as name then the new signal will have the same name as the variable that it is being assigned to.
The Examples section below has a collection of examples on the use of QtCore.Signal().
Note: Signals should be defined only within classes inheriting from QObject.This way the signal information is added to the class QMetaObject structure.
Slots are assigned and overloaded using the decorator QtCore.Slot().Again, to define a signature just pass the types like the QtCore.Signal() class.Unlike the Signal() class, to overload a function, you don't pass every variation as tuple or list.Instead, you have to define a new decorator for every different signature.The examples section below will make it clearer.
Another difference is about its keywords.Slot() accepts a name and a result.The result keyword defines the type that will be returned and can be a C or Python type.name behaves the same way as in Signal().If nothing is passed as name then the new slot will have the same name as the function that is being decorated.
The examples below illustrate how to define and connect signals and slots in PySide2.Both basic connections and more complex examples are given.