Python __Slots__ (创建与使用)

0 投票
2 回答
1577 浏览
提问于 2025-04-17 14:33

我不太明白为什么要创建一个类并使用 __slots__,能不能解释得更清楚一点?

举个例子,我想创建两个类,一个是空的,另一个不是。我到目前为止做到了这个:

class Empty:
    __slots__ =()

def mkEmpty():
    return Empty()

class NonEmpty():
    __slots__ = ('one', 'two')

但是我不知道怎么做“mkNonEmpty”。我对我的 mkEmpty 函数也不太确定。

谢谢

编辑:

这是我最后得到的结果:

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

2 个回答

-2

也许这个文档会对你有帮助?老实说,听起来你现在的水平还不需要担心__slots__这个东西。

6

你需要以传统的方式来初始化你的类。它的工作方式是这样的:

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)

其实,构造函数并不是必须的,也不是很符合 Python 的风格。你可以直接使用类的构造函数,像这样:

ne = NonEmpty(1, 2)

如果你需要的是某种记录,你也可以使用一个空的构造函数,然后在你的应用程序中直接设置属性。

class NonEmpty():
    __slots__ = ('one', 'two')

n = NonEmpty()
n.one = 12
n.two = 15

你需要明白,使用 slots 主要是为了提高性能和节省内存。你不一定要使用它们,通常也不应该使用,除非你知道你的内存有限。只有在真的遇到问题之后,才需要考虑这个。

撰写回答