|  | 
 
| 
“
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  def type_attr():
 Foo1 = type('Foo', (), {'bar': True})
 print(Foo1)
 print(Foo1.bar)
 f = Foo1()
 print(f)
 print(f.bar)
 
 Foochild1 = type('Foochild', (Foo,), {})
 print(Foochild1)
 print(Foochild1.bar)
 
 
 if __name__ == '__main__':
 type_attr()
 ”
 
 这里Foochild1中,必须写Foo1才不会报错。但是我感觉应该写的是Foo呀
 
 本帖最后由 阿奇_o 于 2021-7-6 19:11 编辑 
那是因为 你的 'Foo',只是 父类的名字(是编译器管的),并非 namespace里的 类变量名(人调用的), 
用 globals() 和 locals() 你可以查看到 当前命名空间里的所有 变量名(人认的) 及其对应的值(这是机器才认的)。 
解释器会先从这些变量名字中找,判断是否存在。不存在就会报错。
 复制代码>>> class Person:
        def __init__(self):
                self.name = 'Alice'
                self.age = 18
>>> Emp = type('Employee', (Person,), dict(name='', age=20))
>>> Emp.__bases__
(<class '__main__.Person'>,)
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'Person': <class '__main__.Person'>, 'Emp': <class '__main__.Employee'>}
 | 
 |