__metaclass__ in Python 3

前端 未结 1 828
深忆病人
深忆病人 2020-11-27 06:31

In Python2.7 this code can work very well, __getattr__ in MetaTable will run. But in Python 3 it doesn\'t work.

class MetaTable(ty         


        
相关标签:
1条回答
  • 2020-11-27 07:01

    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.

    0 讨论(0)
提交回复
热议问题