views:

98

answers:

4

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?

+5  A: 

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.

unutbu
And .... voilà! +1.
Manoj Govindan
Now the question is if dynamicObject holds that method in the dictionary only for that use or does it only hold that for that instance (Say within a method)
Programmin Tool
If you have multiple instances of the dynamicObject class, then each of those instances will magically gain the `someMethod` method. But when one of those instances, `someInst`, calls `someInst.someMethod()`, `self` will be equal to `someInst` (as you'd expect).
unutbu
I woud disagree with "this is really an abomination" - it is the correct answer to this question.
jsbueno
I woud disagree with "this is really an abomination" - it is the correct answer to this question.
jsbueno
@unutbu: Thank you very much!
Muhammad Alkarouri
+1  A: 

Why don't you use setattr? I found this way much more explicit.

class dynamicObject(object):
    pass

def method():
    print "Hi"

someObject = dynamicObject()
setattr(someObject,"method", method)
someObject.method()
ohe
Because he wants the object reference `self` to be passed to the method.
Muhammad Alkarouri
+5  A: 

To achieve what you want (create an object for validation by picking and choosing what validation methods I want to add to it), a better way is:

class DynamicObject(object):
    def __init__(self, verify_method = None):
        self.verifier = verify_method
    def verify(self):
        self.verifier(self)

def verify1(self):
    print "verify1"

def verify2(self):
    print "verify2"

obj1 = DynamicObject()
obj1.verifier = verify1

obj2 = DynamicObject(verify2)
#equivalent to
#obj2 = DynamicObject()
#obj2.verify = verify2

obj1.verify()
obj2.verify()
Muhammad Alkarouri
+1: This is much better than dynamically adding methods.
unutbu
A: 

Sometimes it is annoying to need to write a regular function and add it afterwards when the method is very simple. In that case, lambdas can come to the rescue:

    class Square:
        pass

    Square.getX = lambda self: self.x
    Square.getY = lambda self: self.y
    Square.calculateArea = lambda self: self.getX() * self.getY()

Hope this helps.

Baltasarq