我可以为一个类定义 __repr__ 而不是实例吗?
当然可以,我在这里演示一下,使用一个通过 repr 测试的 __repr__。
class Type(type):
def __repr__(cls):
"""
>>> Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
"""
name = cls.__name__
parents = ', '.join(b.__name__ for b in cls.__bases__)
if parents:
parents += ','
namespace = ', '.join(': '.join(
(repr(k), repr(v) if not isinstance(v, type) else v.__name__))
for k, v in cls.__dict__.items())
return 'Type(\'{0}\', ({1}), {{{2}}})'.format(name, parents, namespace)
def __eq__(cls, other):
return (cls.__name__, cls.__bases__, cls.__dict__) == (
other.__name__, other.__bases__, other.__dict__)
并且为了演示:
class Foo(object): pass
class Bar(object): pass
无论是 Python 2:
class Baz(Foo, Bar):
__metaclass__ = Type
或者 Python 3:
class Baz(Foo, Bar, metaclass=Type):
pass
或者相当普遍:
Baz = Type('Baz', (Foo, Bar), {})
>>> Baz
Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
而要进行repr
测试:
def main():
print Baz
assert Baz == eval(repr(Baz))
什么是“repr”测试?它是来自文档中关于“repr”的上述测试。
>>> help(repr)
Help on built-in function repr in module __builtin__:
repr(...)
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.