__metaclass__ in Python3.5

安稳与你 提交于 2019-11-27 04:52:13
Martijn Pieters

Python 3 changed how you specify a metaclass, __metaclass__ is no longer checked.

Use metaclass=... in the class signature:

class Table(object, metaclass=MetaTable):

Demo:

>>> 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>

If you need to provide support for both Python 2 and 3 in your codebase, you can use the six.with_metaclass() baseclass generator or the @six.add_metaclass() class decorator to specify the metaclass.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!