I'm trying to create methods whose names are based on a class' instance's specific attribute. My code is similar to this:
class myClass:
info_to_be_accessed = {
'infoA': 14,
'infoB': 21,
'infoC': False,
'infoD': 'spam'
}
def create_methods(self):
for info in self.info_to_be_accessed:
setattr(self, info, lambda self: self.info_to_be_accessed.get(info, None))
return self
c = myClass().create_methods()
print(c.infoA())
I was expecting c.infoA() to be an instance method, but it turns out as a static method that does not get the self parameter when called. Output raises a TypeError:
Traceback (most recent call last):
File "test.py", line 15, in <module>
print(c.infoA())
TypeError: <lambda>() missing 1 required positional argument: 'self'
Expected output:
14
EDIT: Answering @chepner. I'm honestly not sure this is the best way to deal with it, but my basic problem is that I am dealing with data that is outside my database / my own code. I'm retrieving information from a database I have no control of, so it can be analysed by my code. Basically, my real-code class has a pandas dataframe with information about the result of a complex SQL query and the ability to plot a chart about it, but sometimes I want to filter the dataframe in order to plot it, and sometimes I want to plot the whole thing. I'm not really analyzing a dictionary, but instead creating methods to filter this dataframe. Thing is, the (external) object I'm analyzing with this query has fixed values a certain attribute can be, but if this external database changes in the future, I don't want to create extra code just to cover the new value that is added there. Using methods instead of parameters is just more convenient to me when analyzing this data, but this is not a code that goes to production, merely something I use at the CLI. This is why it's convenient to me to have separate methods for each value that can be passed.
info_to_be_accessedbefore callingcreate_methods? It sounds like you just want a dictionary, not a set of methods. (Or a single methodgetthat performs dictionary lookups for you.)myClassexists is to replace dictionary lookups with method calls. That seems like a huge waste of time and effort. Why go through the hassle of something liked = {'foo': 'bar'}; myClass(d).foo()when you can just used['foo']?