Discuss / Python / 我有个问题

我有个问题

Topic source

FJ-W97

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

class Student(object): __slots__ = ('name', 'age')

s = Student() s.name = 'Bill' s.age = 24 Student.name = 'Michael' Student.age = 10 Student.score = 89 print(s.name, s.age, Student.name, Student.score)

运行之后结果是这样的: Michael 10 Michael 89

为什么会这样?我用__slots__绑定了属性名称。在后面的代码中,我改变类的属性,结果连实例中的属性值也变了 然后我还可以通过类名来增加限定属性之外的新属性,不知道为什么

关注一下,我也不太理解,实例的属性是会覆盖类的属性的,是因为先后顺序造成的吗? 所以我接着你这个往下写的时候: y = Student() y.name = 'Andy' Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'stu' object attribute 'name' is read-only

FJ-W97

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

之前没仔细看教程,__slots__只对类的实例有用,而我误以为对类也有用,就创建了一个本不存在的Student.score之类的.而替换,我觉得是因为实例属性和类属性同名,由于类属性后定义,所以覆盖了之前的实例属性,总的说来,是我粗心大意造成的

amito_

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

可以参考Python官方文档,3.3.2.3.1. Notes on using slots __slots__ are implemented at the class level by creating descriptors (Implementing Descriptors) for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by __slots__; otherwise, the class attribute would overwrite the descriptor assignment.

Ivan蕃

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

用层主的代码测试了一下,发现确实如此,查找了一些资料,希望对大家有用 1,__slots__ 使用之后,实例对象将没有__dict__方法了 2,如果类变量中与slots中的变量重名,这个类变量将变为read only,在class 定义时会错,然而在class定义之外则不会 3,read only会覆盖所有实例的属性,并且在class之外定义的话,以后的实例对象都不能修改实例属性(必须使用类属性)

class Student: slots = ('name','age') s = Student() s.name = 'bill' s.age = 10 Student.name = 'Micheal' Student.age = 11 Student.score = 99 print(s.name,s.age,Student.name,Student.age,Student.score) y = Student() print(y.name) y.name = 'andy'

下面时输出结果:

Traceback (most recent call last): Micheal 11 Micheal 11 99 File "D:/零基础入门学习python/TestModel.py", line 13, in <module>

<blockquote><p>Micheal</p></blockquote> <blockquote><p> y.name = 'andy'</p></blockquote> <blockquote><p>AttributeError: 'Student' object attribute 'name' is read-only</p></blockquote>


  • 1

Reply