0

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')

But I don't know how I would make "mkNonEmpty". I'm also unsure about my mkEmpty function.

Thanks

Edit:

This is what I ended up with:

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
4

2 に答える 2

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)

実際、コンストラクター関数は不要であり、pythonicではありません。次のように、クラスコンストラクタを直接使用できます。使用する必要があります。

ne = NonEmpty(1, 2)

必要なのが何らかのレコードである場合は、空のコンストラクターを使用して、アプリケーションに直接スロットを設定することもできます。

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

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

スロットはパフォーマンス/メモリの理由でのみ必要であることを理解する必要があります。それらを使用する必要はなく、メモリに制約があることがわかっている場合を除いて、おそらく使用しないでください。ただし、これは実際に問題に遭遇した後でのみ発生するはずです。

于 2013-02-02T20:47:16.373 に答える
-2

Maybe the docs will help? Honestly, it doesn't sound like you're at a level where you need to be worrying about __slots__.

于 2013-02-02T20:43:58.213 に答える