__metaclass__是否应该在Python中强制使用元类? [英] Shouldn't __metaclass__ force the use of a metaclass in Python?

查看:83
本文介绍了__metaclass__是否应该在Python中强制使用元类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试学习Python中的元类.我掌握了主要思想,但似乎无法激活该机制.据我了解,在构造类K时,可以通过在全局或类级别将__metaclass__设置为M来将M指定为元类.为了对此进行测试,我编写了以下程序:

I've been trying to learn about metaclasses in Python. I get the main idea, but I can't seem to activate the mechanism. As I understand it, you can specify M to be as the metaclass when constructing a class K by setting __metaclass__ to M at the global or class level. To test this out, I wrote the following program:

p = print

class M(type):
    def __init__(*args):
        type.__init__(*args)
        print("The rain in Spain")

p(1)
class ClassMeta:
    __metaclass__ = M

p(2)
__metaclass__ = M
class GlobalMeta: pass

p(3)
M('NotMeta2', (), {})

p(4)

但是,当我运行它时,会得到以下输出:

However, when I run it, I get the following output:


C:\Documents and Settings\Daniel Wong\Desktop>python --version
Python 3.0.1

C:\Documents and Settings\Daniel Wong\Desktop>python meta.py
1
2
3
The rain in Spain
4

我应该在1和2之后看不到西班牙的雨"吗?这是怎么回事?

Shouldn't I see "The rain in Spain" after 1 and 2? What's going on here?

推荐答案

在Python 3(您正在使用)中,元类由类定义中的关键字参数指定:

In Python 3 (which you are using) metaclasses are specified by a keyword parameter in the class definition:

class ClassMeta(metaclass=M):
  pass

指定__metaclass__类属性或全局变量是Python 2.x的旧语法,不再受支持.另请参见"Python 3的新增功能" PEP 2115 .

Specifying a __metaclass__ class property or global variable is old syntax from Python 2.x and not longer supported. See also "What's new in Python 3" and PEP 2115.

这篇关于__metaclass__是否应该在Python中强制使用元类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆