If everything is an object in python then why does the following not work?
class Hello(object):
def hello(self):
print(x)
h = Hello()
h.hello.x = "hello world"
When doing this I get:
AttributeError: 'instancemethod' object has no attribute 'value'
A way which I can achieve this is by using partial however I am not sure what the effects of that would be on an object. Is there another way to achieve this?
from functools import partial
class Hello(object):
def hello(self, x):
print(x)
h = Hello()
newMethod = partial(h.hello, "helloworld")
newMethod()
Okay, from the comments below, people want a "real" scenario one example which can be considered as the following:
file.txt contains the following list
["ItemID1", "ItemID2", "ItemID3", "ItemID4"]
def BindMethods(self):
# ["ItemID1", "ItemID2", "ItemID3", "ItemID4"]
items = readFromFile("file.txt")
self.bind(AN_EVENT, GenericMethod)
def GenericMethod(self, i, event):
# The person calling this method knows that the method
# only accepts a single argument, not two.
# I am attempting to preserve the interface which I do not have control over
data = generateDataFromID(i)
table[i] = data
The idea here being that you bind a method to an event whereby the caller is expecting the method of a specific signature i.e. a single input argument.
But at the point of binding you want to pass in some extra information down to the handler. You don't know how much information you want to pass down since it is variable.
A expanded/compile time version of the same thing would be something like this:
file.txt contains the following list
["ItemID1", "ItemID2", "ItemID3", "ItemID4"]
def BindMethods(self):
# ["ItemID1", "ItemID2", "ItemID3", "ItemID4"]
items = readFromFile("file.txt")
self.bind(AN_EVENT, self.Item1Method)
self.bind(AN_EVENT, self.Item2Method)
self.bind(AN_EVENT, self.Item3Method)
......
def Item1Method(self, event):
data = generateDataFromID("Item1")
table["Item1ID"] = data
def Item2Method(self, event):
data = generateDataFromID("Item2")
table["Item2ID"] = data