I've defined a class like this:
class MyClass:
def GetValue(self):
return 5
def PrintValue(self):
print self.GetValue()
For some instances of MyClass I need to re-define the GetValue() dinamically, i.e. something like this:
def GetAGoodValue(self):
return 7
oneObject=MyClass()
oneObject.GetValue=GetAGoodValue
oneObject.PrintValue()
After re-defining I get the errror:
TypeError: not enough arguments; expected 1, got 0
If inside the PrintValue method I code instead:
print self.GetValue(self)
then the above code works, but only for those MyClass instances where the GetValue method is re-defined. Instances where the GetValue method is not re-defined yeld the error:
TypeError: too many arguments; expected 1, got 2
Any suggestion?
If you assign a method to a single object instead of changing the whole class, you have to implement the ususally-done binding yourself.
So you have two options:
Either you do
oneObject.GetValue = lambda: GetAGoodValue(oneObject)
or you "ask" the function object what it would do if called as a class attribute:
oneObject.GetValue = GetAGoodValue.__get__(oneObject, MyClass)
so that it works as intended.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments