python - 我的 __dict__ 在哪里?从命名元组继承的类
问题描述
当我从命名元组继承一个类时,为什么__dict__
是空的?以下是准备展示的最少代码。你可以看到它x.__dict__
是空的,但z.__dict__
有信息。
from collections import namedtuple
Person = namedtuple('Person', 'name age')
class Student(Person):
def print(self):
print(self.name)
x = Student("Tom",25)
class Employee:
def __init__(self,name, age):
self._name = name
self._age = age
y = Employee("Jerry",24)
class MyEmployee(Employee):
def print(self):
print(self._name)
z = MyEmployee("John",22)
print(x.__dict__)
print(y.__dict__)
print(z.__dict__)
这是输出
{}
{'_name': 'Jerry', '_age': 24}
{'_name': 'John', '_age': 22}
解决方案
简而言之:没有一个开始。Person("Alice", 21).__dict__
你可以通过过牌甚至只是过牌来测试它("Alice", 21).__dict__
,你会看到他们都加注AttributeError
。如果查看 的源代码,namedtuple
您会发现 a 的 construtor( __new__()
) 与 a的 construtor()namedtuple
相同tuple
。如果你查看 的源代码,tuple.__new__
你会发现__dict__
从来没有被创建过。
您看到的空 dict 来自您将 a 子类化的事实namedtuple
。后两个填充在您的__init__
函数中。但是由于在您的Student
类中的初始化程序期间没有做任何事情,所以它__dict__
是空的。
推荐阅读
- google-cloud-platform - GCP的“Longrunningrecognize”输出数据是什么格式的?
- html - 在 bash 脚本中发送邮件时读取字符串消息中的 HTML
- neo4j - Neo4j 中的组和最小关系属性
- javascript - 打开自动创建的pdf php javascript时出现奇怪的语法
- r - 在传单地图中绘制颜色区域
- javascript - 在 for 循环中加载函数 - 变量函数名 [变量]
- r - 使用过滤器时没有得到预期的结果
- java - Java,如何编写或添加而不是覆盖文本文件?
- regex - Perl正则表达式捕获行首和行尾之间的字符串(行尾有一个空格)
- javascript - 运行此 jsp 页面时,我不断收到错误消息