I do understand how setattr()
works in python, but my question is when i try to dynamically set an attribute and give it an unbound function as a value, so the attribute is a callable, the attribute ends up taking the name of the unbound function when i call attr.__name__
instead of the name of the attribute.
Here's an example:
I have a Filter
class:
class Filter:
def __init__(self, column=['poi_id', 'tp.event'], access=['con', 'don']):
self.column = column
self.access = access
self.accessor_column = dict(zip(self.access, self.column))
self.set_conditions()
def condition(self, name):
# i want to be able to get the name of the dynamically set
# function and check `self.accessor_column` for a value, but when
# i do `setattr(self, 'accessor', self.condition)`, the function
# name is always set to `condition` rather than `accessor`
return name
def set_conditions(self):
mapping = list(zip(self.column, self.access))
for i in mapping:
poi_column = i[0]
accessor = i[1]
setattr(self, accessor, self.condition)
In the class above, the set_conditions
function dynamically set attributes (con
and don
) of the Filter class and assigns them a callable, but they retain the initial name of the function.
When i run this:
>>> f = Filter()
>>> print(f.con('linux'))
>>> print(f.con.__name__)
Expected:
- linux
- con (which should be the name of the dynamically set attribute)
I get:
- linux
- condition (name of the value (unbound
self.condition
) of the attribute)
But i expect f.con.__name__
to return the name of the attribute (con
) and not the name of the unbound function (condition
) assigned to it.
Can someone please explain to me why this behaviour is such and how can i go around it?
Thanks.