子类与父类的属性限制的继承关系
Topic source我的理解是: B 也是Student的实例. 所以Student 的 __slots__ = ('name','score')和 Classmates的__slots__ = ('name') 两者的集合Union都可以动态定义. 所以没有矛盾啊.
当父类没有__slots__
属性,而子类有__slots__
属性时,子类的属性仍然可以动态地修改和定义。这是因为__slots__
属性只会影响类的实例的属性,而不会影响类本身的属性。
子类继承了父类的属性,包括动态修改和定义属性的能力。当父类没有__slots__
属性时,子类继承的属性的动态修改和定义能力不会受到任何限制。当子类定义了__slots__
属性时,子类的实例会受到__slots__
属性的约束,只能拥有__slots__
中定义的属性,但是子类本身仍然可以动态地修改和定义属性。
On1on#6楼,说错了,父类没有
__slots__
而子类有
__slots__
的时候,子类实例不受子类中
__slots__
中定义的属性约束,可以自己定义attribute。
不信自己运行下述代码:
import sys
import os
from types import MethodType
class Student(object):
def __init__(self, name):
self.name = name
class Classmate(Student):
__slots__ = ('name')
def __init__(self,name):
self.name =name
B = Classmate('ami')
B.gender = 'female'
print(B.gender)
- 1
alienation
经测试,有如下几种情况:
父类有slots限制,子类没有
父类有slots子类也有
父类没有slots,子类没有
父类没有slots,子类有
在第一,第三和第四种情况下,子类的属性都是可以任意动态定义的
只有在第二种情况下有限制,子类的可动态定义属性为父类和子类slots的并集
class Student(object):
__slots__ = ('name','score')
def __init__(self, name):
self.name = name
class Classmate(Student):
__slots__ = ('name')
def __init__(self,name):
self.name =name
B = Classmate('ami')
B.score = 90
B.gender = 'female'