如何在不修改类的情况下使len()在类的不同实例上使用不同的方法工作? [英] How to make len() work with different methods on different instances of a class, without modifying the class?

查看:94
本文介绍了如何在不修改类的情况下使len()在类的不同实例上使用不同的方法工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不修改类的情况下使len()与实例方法一起使用?

Is there a way to make len() work with instance methods without modifying the class?

我的问题的示例:

>>> class A(object):
...     pass
...
>>> a = A()
>>> a.__len__ = lambda: 2
>>> a.__len__()
2
>>> len(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'A' has no len()

注意:

  • A的不同实例将附加不同的__len__方法
  • 我无法更改课程A
  • different instances of A will have different __len__ methods attached
  • I cannot change the class A

推荐答案

实际上可以不基于此 answer ,Alex Martelli:

It is actually possible without modifying the class based on this answer by Alex Martelli:

class A(object):
    def __init__(self, words):
        self.words = words

    def get_words(self):
        return self.words


a = A("I am a")
b = A("I am b")

def make_meth(inst, _cls, meth, lm):
    inst.__class__ = type(_cls.__name__, (_cls,), {meth: lm})

make_meth(a, A, "__len__", lambda self: 12)
make_meth(b, A, "__len__", lambda self: 44)

print(len(b))
print(len(a))
print(a.get_words())
print(b.get_words())

如果我们运行代码:

In [15]: a = A("I am a")    
In [16]: b = A("I am b")    
In [17]: make_meth(a, A, "__len__", lambda self: 12)
In [18]: make_meth(b, A, "__len__", lambda self: 44) 
In [19]: print(len(b))
44    
In [20]: print(len(a))
12

In [21]: print(a.get_words())
I am a    
In [22]: print(b.get_words())
I an b

根据链接答案最后一部分的最后一部分,使用inst.__class__ = type(...后,您可以使用inst.specialmethod在每个实例的基础上添加任何方法:

As per the last part of the last part of the linked answer, you can add any methods on a per instance basis using inst.specialmethod once you have used inst.__class__ = type(... :

In [34]: b.__class__.__str__ =  lambda self: "In b"

In [35]: print(str(a))
<__main__.A object at 0x7f37390ae128>

In [36]: print(str(b))
In b

这篇关于如何在不修改类的情况下使len()在类的不同实例上使用不同的方法工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆