python - 子类化多个类时来自 __dict__ 中的实例属性
问题描述
我正在从多个类中继承。当我打印实例属性时,self.__dict__
只包含 First 类的属性。我怎样才能同时包含第二个属性?
class Third(First,Second):
def __init__(self):
super().__init__()
print (self.__dict__)
解决方案
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'}
推荐阅读
- c# - 即使输入与模拟输入值不匹配,最小起订量函数调用也始终返回值
- c# - VS2017 自动将项目配置平台设置添加到解决方案 .sln 文件
- java - “onRadioButtonClicked”方法不适用于“onCreate”方法实现的单选按钮
- r - corrplot 的奇怪行为
- documentation - Doxygen 默认注释
- python - Flask-User / Flask-WTForms 中的 reCAPTCHA:“网站验证 reCAPTCHA 通过解决方案的时间少于 50%”?
- ios - 尝试下载文件时出现 Swift Alamofire 错误
- c# - 在 LINQ 选择中使用公式
- javascript - 本机 JS Ajax 向 ASP.Net 发布的对象为空
- c# - C#打印机本地打印机安装处理