Discuss / Python / 子类与父类的属性限制的继承关系

子类与父类的属性限制的继承关系

Topic source

alienation

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

经测试,有如下几种情况:

父类有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'

SamlPan

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

越说越乱,大家不要看这个回复,自己去理解,就懂了

Eok

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

我觉得说的挺全面的啊,哪里乱了

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

第四种也是动态定义吗?不是受他自身的__slots__所限制吗

kc

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

我的理解是: B 也是Student的实例. 所以Student 的 __slots__ = ('name','score')和 Classmates的__slots__ = ('name') 两者的集合Union都可以动态定义. 所以没有矛盾啊.

On1on

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

当父类没有__slots__属性,而子类有__slots__属性时,子类的属性仍然可以动态地修改和定义。这是因为__slots__属性只会影响类的实例的属性,而不会影响类本身的属性。

子类继承了父类的属性,包括动态修改和定义属性的能力。当父类没有__slots__属性时,子类继承的属性的动态修改和定义能力不会受到任何限制。当子类定义了__slots__属性时,子类的实例会受到__slots__属性的约束,只能拥有__slots__中定义的属性,但是子类本身仍然可以动态地修改和定义属性。

明天过后.

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

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

Reply