Python3.5中的__metaclass__

时间:2016-08-18 08:23:45

标签: python python-3.5 metaclass

在Python2.7中,此代码可以很好地运行,__getattr__ MetaTable 会跑。但是在Python 3.5中它不起作用。

class MetaTable(type):
    def __getattr__(cls, key):
        temp = key.split("__")
        name = temp[0]
        alias = None

        if len(temp) > 1:
            alias = temp[1]

        return cls(name, alias)


class Table(object):
    __metaclass__ = MetaTable

    def __init__(self, name, alias=None):
        self._name = name
        self._alias = alias


d = Table
d.student__s

但是在Python 3.5中,我得到了一个属性错误:

Traceback (most recent call last):
  File "/Users/wyx/project/python3/sql/dd.py", line 31, in <module>
    d.student__s
AttributeError: type object 'Table' has no attribute 'student__s'

1 个答案:

答案 0 :(得分:29)

不再检查Python 3 changed how you specify a metaclass__metaclass__

在班级签名中使用metaclass=...

class Table(object, metaclass=MetaTable):

演示:

>>> class MetaTable(type):
...     def __getattr__(cls, key):
...         temp = key.split("__")
...         name = temp[0]
...         alias = None
...         if len(temp) > 1:
...             alias = temp[1]
...         return cls(name, alias)
...
>>> class Table(object, metaclass=MetaTable):
...     def __init__(self, name, alias=None):
...         self._name = name
...         self._alias = alias
...
>>> d = Table
>>> d.student__s
<__main__.Table object at 0x10d7b56a0>

如果您需要在代码库中为Python 2和3提供支持,则可以使用six.with_metaclass() baseclass generator@six.add_metaclass() class decorator来指定元类。