Is it possible to add a method to an object class, and use it on all objects?
In Python attributes are implemented using a dictionary :
>>> t = test()
>>> t.__dict__["foo"] = "bla"
>>> t.foo
'bla'
But for "object", it uses a 'dictproxy' as an interface to prevent such assignement :
>>> object.__dict__["test"] = "test"
TypeError: 'dictproxy' object does not support item assignment
So no, you can't.
NB : you can't modify the metaclass Type directly neither. But as Python is very flexible, I am sure a Guru could find a way to achieve what you want. Any black wizard around here :-) ?
No, Python's internals take great care to make built-in types NOT mutable -- very different design choices from Ruby's. It's not possible to make object "monkeypatchable" without deeply messing with the C-coded internals and recompiling the Python runtime to make a very different version (this is for the classic CPython, but I believe exactly the same principle holds for other good implementations such as Jython and IronPython, just s/C/Java/ and S/C/C#/ respectively;-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With