小编Dan*_*Liu的帖子

子类_​​_module__在手动创建类型为()的新类时设置为元类模块

在下面的示例中,新创建的子类最终是元类__module__而不是父类的模块.我只是在使用时才看到这种情况,ABCMeta所以它可能是该模块的特定内容,任何人都知道可能会发生什么?

In [1]: from abc import ABCMeta

In [2]: class test(metaclass=ABCMeta):
   ...:     pass
   ...: 

In [3]: newclass = type('newclass', (test,), {})

In [4]: newclass.__module__
Out[4]: 'abc'
Run Code Online (Sandbox Code Playgroud)

当我以更标准的方式定义子类时,我想要的行为发生:

In [5]: class subtest(test):
   ...:     pass
   ...: 

In [6]: subtest.__module__
Out[6]: '__main__'
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么会这样,并且如何使用type,创建一个具有正确__module__属性的新子类(例如__module__=='__main__')?

python metaprogramming metaclass python-3.x

4
推荐指数
1
解决办法
106
查看次数

标签 统计

metaclass ×1

metaprogramming ×1

python ×1

python-3.x ×1