Search code examples
pythonselfdynamic-method

Python: using Self and adding methods to an object on the fly


Here's my idea: Start with a simple object:

class dynamicObject(object):
    pass

And to be able to add pre written methods to it on the fly:

def someMethod(self):
    pass

So that I can do this:

someObject = dyncamicObject()
someObject._someMethod = someMethod
someObject._someMethod()

Problem is, it wants me to specify the self part of _someMethod() so that it looks like this:

someObject._someMethod(someObject)

This seems kind of odd since isn't self implied when a method is "attached" to an object?

I'm new to the Python way of thinking and am trying to get away from the same thought process for languages like C# so the idea here it to be able to create an object for validation by picking and choosing what validation methods I want to add to it rather than making some kind of object hierarchy. I figured that Python's "self" idea would work in my favor as I thought the object would implicitly know to send itself into the method attached to it.

One thing to note, the method is NOT attached to the object in any way (Completely different files) so maybe that is the issue? Maybe by defining the method on it's own, self is actually the method in question and therefore can't be implied as the object?


Solution

  • Although below I've tried to answer the literal question, I think Muhammad Alkarouri's answer better addresses how the problem should actually be solved.


    Add the method to the class, dynamicObject, rather than the object, someObject:

    class dynamicObject(object):
        pass
    
    def someMethod(self):
        print('Hi there!')
    
    someObject=dynamicObject()
    dynamicObject.someMethod=someMethod
    someObject.someMethod()
    # Hi there!
    

    When you say someObject.someMethod=someMethod, then someObject.__dict__ gets the key-value pair ('someMethod',someMethod).

    When you say dynamicObject.someMethod=someMethod, then someMethod is added to dynamicObject's __dict__. You need someMethod defined in the class for someObject.someMethod to act like a method call. For more information about this, see Raymond Hettinger's essay on descriptors -- after all, a method is nothing more than a descriptor! -- and Shalabh Chaturvedi's essay on attribute lookup.


    There is an alternative way:

    import types
    someObject.someMethod=types.MethodType(someMethod,someObject,type(someObject))
    

    but this is really an abomination since you are defining 'someMethod' as a key in someObject.__dict__, which is not the right place for methods. In fact, you do not get a class method at all, just a curried function. This is more than a mere technicality. Subclasses of dynamicObject would fail to inherit the someMethod function.