Class __repr__ 属于元 class,而不是 class

Class __repr__ of a metaclass, not a class

我知道可以使用元class 定义'class repr'。但是,我需要 returning metaclass 和它自己的 __repr__ 这样的功能:

class Meta(type):
    def __repr__(cls):
        return 'Person class: {}'.format(cls.__name__)


class Person(metaclass=Meta):
    def __init__(self, name, age, job):
        self.name = name
        self.job = job
        self.age = age

    def __str__(self):
        return 'Person: {}, {}, {}'.format(self.name,
                                           self.age,
                                           self.job)


class Employee(Person):
    def __init__(self, name, age):
        super(Employee, self).__init__(name, age, 'employee')


class Manager(Person):
    def __init__(self, name, age):
        super(Manager, self).__init__(name, age, 'manager')

m = Manager('bob', 79)
e = Employee('stephen', 25)

正如预期的那样,type(e)type(m) return 各自的 'Person class: ...',但是,如果我这样做 type(Employee),我会得到 <class '__main__.Meta'> .我需要这个 class 有它自己的 __repr__ 因为我正在使用的实际实现包括一个基础 Type class 和 [=23 的子 classes =]、Number 等。在实例上调用 type 工作正常,但由于 type 也可能在 class 上调用,我需要更多 'user-friendly' return 字符串.

找到一个简单的解决方案。由于我的class结构(继承树)如下,我只需要return下class下:

MetaType: metaclass with __repr__
 |
Type: base class
 |
builtins: e.g. String, Number

所以我在代码中输入的是这样的:

t = type(self.parse(args['object']))
# where 'self.parse' is the parsing method for the argument to my function
# where args['object'] is the object whose type is being returned
if t == MetaType:
    return Type
return t

实际上,没有什么可以阻止您使用 __repr__ 为元 class 本身编写元元 class:

In [2]: class MM(type):
   ...:     def __repr__(cls):
   ...:         return f"<metaclass {cls.__name__}"
   ...:      

In [3]: class M(type, metaclass=MM):
   ...:     def __repr__(cls):
   ...:         return f"<class {cls.__name__}>"
   ...:     

In [4]: class O(metaclass=M):
   ...:     pass
   ...: 

In [5]: o = O()

In [6]: o
Out[6]: <<class O> at 0x7ff7e0089128>

In [7]: O
Out[7]: <class O>

repr(M)的输出:

In [8]: repr(M)
Out[8]: '<metaclass M'

(这里令人困惑的是 type 也是 type 本身的元 class - 这反映在 M 没有继承自 MM ,而是将其作为元class).