鱼C论坛

 找回密码
 立即注册
查看: 1294|回复: 1

[已解决]我用type创建类想要继承父类的时候为什么这里会报错

[复制链接]
发表于 2021-7-6 16:20:34 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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呀
最佳答案
2021-7-6 19:10:21
本帖最后由 阿奇_o 于 2021-7-6 19:11 编辑

那是因为 你的 'Foo',只是 父类的名字(是编译器管的),并非 namespace里的 类变量名(人调用的),
用 globals() 和 locals() 你可以查看到 当前命名空间里的所有 变量名(人认的) 及其对应的值(这是机器才认的)。
解释器会先从这些变量名字中找,判断是否存在。不存在就会报错。
  1. >>> class Person:
  2.         def __init__(self):
  3.                 self.name = 'Alice'
  4.                 self.age = 18

  5. >>> Emp = type('Employee', (Person,), dict(name='', age=20))
  6. >>> Emp.__bases__
  7. (<class '__main__.Person'>,)
  8. >>> globals()
  9. {'__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'>}
复制代码


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-7-6 19:10:21 | 显示全部楼层    本楼为最佳答案   
本帖最后由 阿奇_o 于 2021-7-6 19:11 编辑

那是因为 你的 'Foo',只是 父类的名字(是编译器管的),并非 namespace里的 类变量名(人调用的),
用 globals() 和 locals() 你可以查看到 当前命名空间里的所有 变量名(人认的) 及其对应的值(这是机器才认的)。
解释器会先从这些变量名字中找,判断是否存在。不存在就会报错。
  1. >>> class Person:
  2.         def __init__(self):
  3.                 self.name = 'Alice'
  4.                 self.age = 18

  5. >>> Emp = type('Employee', (Person,), dict(name='', age=20))
  6. >>> Emp.__bases__
  7. (<class '__main__.Person'>,)
  8. >>> globals()
  9. {'__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'>}
复制代码


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-20 01:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表