Skip to main content
 首页 » 编程设计

python之无法将 __repr__/__str__ 动态绑定(bind)到使用类型创建的类

2025年05月04日16lhb25

<分区>

我正在为 python 滚动我自己的 Enum 类,但我无法让 __str__ 和 __repr__ 正常工作,这是什么我做错了吗?

In [2]: x = Enum(X=1, Y=2) 
 
In [3]: x 
Out[3]: common.utils.Enum 
 
In [4]: str(x) 
Out[4]: "<class 'common.utils.Enum'>" 
 
In [5]: x.__repr__ 
Out[5]: <bound method type.reprfun of <class 'common.utils.Enum'>> 
 
In [6]: x.__repr__() 
Out[6]: 'Enum(Y=2, X=1)'  

代码本身:

def Enum(*args, **kwargs): 
    enums = dict(zip(args, range(len(args))), **kwargs) 
    def reprfun(self): 
        res = 'Enum(' +\ 
            ', '.join(map(lambda x: '{}={}'.format(x[0],x[1]), enums.items())) +\ 
            ')' 
        return res 
 
    reverse = dict((value, name) for name, value in enums.items()) 
    typedict = enums.copy() 
    typedict['name'] = reverse 
    instance = type('Enum', (), typedict) 
    instance.__repr__ = types.MethodType(reprfun, instance) 
    instance.__str__ = types.MethodType(reprfun, instance) 
    return instance