首页 > 解决方案 > 子类化多个类时来自 __dict__ 中的实例属性

问题描述

我正在从多个类中继承。当我打印实例属性时,self.__dict__只包含 First 类的属性。我怎样才能同时包含第二个属性?

class Third(First,Second):

    def __init__(self):

        super().__init__()
        print (self.__dict__)

标签: pythoninheritance

解决方案


super().__init__仅在方法解析顺序中调用__init__来自下一个超类的调用。然后下一个类方法的角色也调用.super().__init__

错误的

class First:
    def __init__(self):
        self.foo = 'foo'


class Second:
    def __init__(self):
        self.bar = 'bar'


class Third(First,Second):
    def __init__(self):
        super().__init__()
        print(self.__dict__)

Third() # prints: {'foo': 'foo'}

class First:
    def __init__(self):
        self.foo = 'foo'
        super().__init__()


class Second:
    def __init__(self):
        self.bar = 'bar'
        super().__init__()


class Third(First,Second):
    def __init__(self):
        super().__init__()
        print(self.__dict__)

Third() # prints: {'foo': 'foo', 'bar': 'bar'}

推荐阅读