简体   繁体   English

Python __slots__不适用于某些类声明

[英]Python __slots__ doesn't work with a certain class declaration

When I declare the class in python as below slots work 当我在python中声明以下类的插槽时工作

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 当我在python中声明以下类的类时, 插槽不起作用

   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. 首先, class声明中缺少的括号。

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). __slots__属性仅在“新样式”类中起作用(它们并不是真正的“新”类,它们在Python 2.2中已经出现15年多了)。 In Python 2, you only get a new-style class if you inherit from object (or from some other new-style class). 在Python 2中,如果您继承自object (或其他某种新样式类),则只会获得一个新样式类。 Inheritance is declared by putting one or more base classes in parentheses after the derived class's name in the class statement. 通过将一个或多个基类放在class声明中派生类名称之后的括号中来声明继承。 So your second implementation of CSStudent is not a new-style class, since it does not inherit from anything. 因此,您的CSStudent的第二个实现不是新型类,因为它不继承任何东西。 Thus __slots__ won't work (it will just be a weirdly named attribute). 因此__slots__不起作用(它只是一个奇怪的命名属性)。

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 ). 新样式类和旧样式类之间的区别仅在Python 2上存在。Python3删除了旧样式类,因此您的两个类实现在Python 3解释器中的工作方式相同(不再需要显式继承自object )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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