Python __Slots __(制作和使用) [英] Python __Slots__ (Making and Using)
问题描述
我并没有真正上过课,可以使用__slots__
使其更清晰吗?
I don't really get making a class and using __slots__
can someone make it clearer?
例如,我正在尝试创建两个类,一个是空的,另一个不是.到目前为止,我已经知道了:
For example, I'm trying to make two classes, one is empty the other isn't. I got this so far:
class Empty:
__slots__ =()
def mkEmpty():
return Empty()
class NonEmpty():
__slots__ = ('one', 'two')
但是我不知道如何制作"mkNonEmpty".我也不确定我的mkEmpty函数.
But I don't know how I would make "mkNonEmpty". I'm also unsure about my mkEmpty function.
谢谢
这就是我最终得到的:
class Empty:
__slots__ =()
def mkEmpty():
return Empty()
class NonEmpty():
__slots__ = ('one', 'two')
def mkNonEmpty(one,two):
p = NonEmpty()
p.one= one
p.two= two
return p
推荐答案
然后,您必须以传统方式初始化您的类.它将像这样工作:
You then have to initialize your class in a traditional way. It will work like this :
class Empty:
__slots__ =()
def mkEmpty():
return Empty()
class NonEmpty():
__slots__ = ('one', 'two')
def __init__(self, one, two):
self.one = one
self.two = two
def mkNonEmpty(one, two):
return NonEmpty(one, two)
实际上,构造函数是不必要和非pythonic的.您可以并且应该直接使用类构造函数,如下所示:
Actually, the constructor functions are non-necessary and non pythonic. You can, and should use the class constructor directly, like so :
ne = NonEmpty(1, 2)
如果您需要某种记录,也可以使用空的构造函数并直接在应用程序中设置插槽
You can also use an empty constructor and set the slots directly in your application, if what you need is some kind of record
class NonEmpty():
__slots__ = ('one', 'two')
n = NonEmpty()
n.one = 12
n.two = 15
您需要了解,仅出于性能/内存原因才需要插槽.您不需要使用它们,也可能不应该使用它们,除非您知道自己的内存有限.不过,这只应该在实际陷入问题之后.
You need to understand that slots are only necessary for performance/memory reasons. You don't need to use them, and probably shouldn't use them, except if you know that you are memory constrained. This only should be after actually stumbling into a problem though.
这篇关于Python __Slots __(制作和使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!