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
Ecco
  • 27
  • 6

2 Answers2

6

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)

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.

raph.amiard
  • 2,755
  • 2
  • 20
  • 23
  • Thanks, that was very helpful. Would you mind taking a look at my edit and telling me if its alright or not? – Ecco Feb 02 '13 at 21:02
  • Well it works. Do you have any particular reason to be using a function to initialize your object rather than the class constructor like in my example though ? – raph.amiard Feb 02 '13 at 21:04
  • Yeah, we have to do it the "dumb" way *sigh* it's for a lab. – Ecco Feb 02 '13 at 21:06
-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__.

Hank Gay
  • 70,339
  • 36
  • 160
  • 222