首页 > 解决方案 > 我的 __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}

标签: pythonpython-3.x

解决方案


简而言之:没有一个开始。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__是空的。


推荐阅读