Dynamically assign special methods to objects but not classes in Python

后端 未结 3 728
情书的邮戳
情书的邮戳 2020-12-18 10:07

I would like to do the following:

class A(object): pass

a = A()
a.__int__ = lambda self: 3

i = int(a)

Unfortunately, this throws:

3条回答
  •  星月不相逢
    2020-12-18 10:41

    The only recourse that works for new-style classes is to have a method on the class that calls the attribute on the instance (if it exists):

    class A(object):
        def __int__(self):
            if '__int__' in self.__dict__:
                return self.__int__()
            raise ValueError
    
    a = A()
    a.__int__ = lambda: 3
    int(a)
    

    Note that a.__int__ will not be a method (only functions that are attributes of the class will become methods) so self is not passed implicitly.

提交回复
热议问题