简体   繁体   中英

Python __slots__ doesn't work with a certain class declaration

When I declare the class in python as below slots work

class CSStudent(object):
stream = 'cse'
__slots__ = ['name', 'roll']

def __init__(self, name, roll):
    self.name = name
    self.roll = roll

When I declare the class in python as below slots doesn't work

   class CSStudent:
stream = 'cse'
__slots__ = ['name', 'roll']

def __init__(self, name, roll):
    self.name = name
    self.roll = roll

Two things seem to have triggered your error:

First, the missing brackets from the class declaration.

Second, your indents were way out of line. Four spaces for each new block of code.

class CSStudent(object):
    stream = 'cse'
    __slots__ = ['name', 'roll']

    def __init__(self, name, roll):
        self.name = name
        self.roll = roll 

user247=CSStudent('user247',2018)

print user247.name,' | ',user247.roll

When you run this, works just fine:

$ chmod +x /tmp/slots_test.py 
$ /tmp/slots_test.py 
user247  |  2018

The __slots__ attribute only works in "new-style" classes (which are not really "new", they came out in Python 2.2 more than 15 years ago). In Python 2, you only get a new-style class if you inherit from object (or from some other new-style class). Inheritance is declared by putting one or more base classes in parentheses after the derived class's name in the class statement. So your second implementation of CSStudent is not a new-style class, since it does not inherit from anything. Thus __slots__ won't work (it will just be a weirdly named attribute).

The distinction between new-style and old-style classes only exists on Python 2. Python 3 has dropped old-style classes, so both of your class implementations would work the same in a Python 3 interpreter (it's no longer required to explicitly inherit from object ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM