2

这个答案到“什么是元类?” 我懂了:

您首先编写类 Foo(object),但类对象 Foo 尚未在内存中创建。

Python 将在类定义中查找元类。如果找到它,它将使用它来创建对象类 Foo。如果没有,它将使用 type 来创建类。

经过测试,似乎类的属性是在类的构造函数运行之前实例化的。我有什么误解?

测试代码:

class meta(type):

    def __init__(cls, name, bases, dic):
        type.__init__(cls, name, bases, dic)

        print hasattr(cls, "a")
        cls.a = "1"


class A(object):
    a = "a"
    __metaclass__ = meta


class B(object):
    __metaclass__ = meta


class C(object):
    __metaclass__ = meta
    a = "a"


print A.a
print B.a
print C.a

输出:

True
False
True
1
1
1
4

1 回答 1

4

类体在类构建之前运行,是的。

The body of the class provides a temporary namespace, and all local names in that namespace are given as a dictionary to construct the class object, together with the base classes and a name for the class.

You can do this with the type() constructor too:

>>> Foo = type('Foo', (), {'a': 1})
>>> Foo.a
1

The class body is basically executed as a function, with the local namespace of that function being used to create the class attributes, the 3rd argument to type() above.

In python 3 you have a little more influence on that process with the __prepare__ hook on a metaclass. __prepare__ should be a class method that returns a initial namespace for the class body; use it to inject extra names into the generated class body before the class body is executed:

class MyMeta(type):
   @classmethod
   def __prepare__(mcl, name, bases):
       return {'a': 1}
于 2013-01-24T15:43:39.860 回答