Discuss / Python / 父类中的__slots__对子类不起作用

父类中的__slots__对子类不起作用

Topic source

Ethann

#1 Created at ... [Delete] [Delete and Lock User]

以下代码是在IDLE中运行的,直接复制粘贴在.py文件中无法运行的。

class Student(object):
    __slots__ = ('name', 'age')
    def set_score(self,score):
        self.score = score
        
s = Student() #类的实例化
s.name = 'Hnali' #给Student类绑定name属性

s.name
'Hnali'

s.age = 24
s.age
24

s.score = 100 #由于__slots__方法,不能给Student类绑定score属性
Traceback (most recent call last):
  File "C:\Users\***\AppData\Local\Programs\Python\Pyt**n310\lib\co**e.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'

s.set_score(100) #尽管在Student类中定义了set_score方法,也不能绑定score属性
Traceback (most recent call last):
  File "C:\Users\***\AppData\Local\Pro**ams\Python\Python310\l**b\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<input>", line 4, in set_score
AttributeError: 'Student' object has no attribute 'score'

父类中的__slots__方法对子类不起作用。

class PrimaryStudent(Student):
    pass

ps = PrimaryStudent()

ps.name = 'asj'
ps.age = 24

ps.height = 18 

s.height = 18 #s是父类Student的实例化,可以看到s.heigh会引起AttributeError错误。二上面的PrimaryStudent子类可以绑定height属性。
Traceback (most recent call last):
  File "C:\Users\***\AppData\Local\Pr***ms\Python\Pyth****10\lib\***e.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'height'

ps.set_score(99) #父类Student中的set_score方法在子类PrimaryStudent中可以正常使用。
ps.score
99

王小胖、

#2 Created at ... [Delete] [Delete and Lock User]

使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的。

除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__


  • 1

Reply