Python 元类的类,而不是类
我知道通过使用元类定义Python 元类的类,而不是类,python,python-3.x,oop,metaclass,repr,Python,Python 3.x,Oop,Metaclass,Repr,我知道通过使用元类定义'classrepr'的能力。但是,我需要返回元类及其自己的\uuuu repr\uuu的功能: class Meta(type): def __repr__(cls): return 'Person class: {}'.format(cls.__name__) class Person(metaclass=Meta): def __init__(self, name, age, job): self.name = na
'classrepr'
的能力。但是,我需要返回元类及其自己的\uuuu repr\uuu
的功能:
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)
返回各自的'Person class:…'
,但是,如果我执行type(Employee)
,我会得到
。我需要这个类有自己的\uuuu repr\uuuu
,因为我使用的实际实现由一个基本类型
类和字符串
、数字
等子类组成。在实例上调用类型可以很好地工作,但由于类型也可以在类上调用,我需要一个更“用户友好”的返回字符串 找到了一个简单的解决方案。由于我的类结构(继承树)如下所示,我只需要返回下一个类:
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
实际上,没有什么可以阻止您使用元类本身的
\uuuu repr\uuuu
编写一个元类:
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>
(这里令人困惑的是,
type
也是type
本身的元类——这反映在这里,M不是继承自MM
,而是将其作为元类)。您可以添加repr(M)
的输出吗?这就是我要找的部分。@NChauhan你应该养成自己检查这些东西的习惯。无论如何,当我运行它时,我看到repr(M)
是“创造性的!我应该检查一下:-)Python元类毕竟也是类。
In [8]: repr(M)
Out[8]: '<metaclass M'