1

How do I add magic method to an existing object using partial? (I understand that adding methods to an existing object is not a recommended concept.)

Here's what I've tried

from functools import partial 
class Foo:
  def __init__(self):
    self.value = 10

def my_function(obj):
  return str(obj.value)

obj = Foo()
obj.__repr__ = partial(my_function, obj)
print(repr(obj))         # <__main__.A object at 0x7ff612e62bb0>
print(obj.__repr__())    # 10

I was expecting print(repr(obj)) also prints 10, but it just returned memory address.

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
kkomacat
  • 11
  • 1
  • Welcome to Stack Overflow! Please take the [tour]. Please [edit] and fix the indenting of your code. At the moment, you have an `IndentationError` at `self.value = 10`. For more tips, see [ask]. – wjandrea Jul 29 '22 at 04:41
  • `partial` is in `functools`. `from functools import partial` – wjandrea Jul 29 '22 at 04:43
  • Does this answer your question? [Overriding special methods on an instance](https://stackoverflow.com/questions/10376604/overriding-special-methods-on-an-instance) – wjandrea Jul 29 '22 at 04:54

0 Answers0