【发布时间】:2019-08-09 23:55:21
【问题描述】:
我确实了解setattr() 在 python 中的工作原理,但我的问题是,当我尝试动态设置属性并为其提供未绑定函数作为值时,因此该属性是可调用的,该属性最终取名当我调用 attr.__name__ 而不是属性的名称时,未绑定函数。
这是一个例子:
我有一个Filter 类:
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)
在上面的类中,set_conditions 函数动态设置 Filter 类的属性(con 和 don)并为其分配一个可调用对象,但它们保留了函数的初始名称。
当我运行这个时:
>>> f = Filter()
>>> print(f.con('linux'))
>>> print(f.con.__name__)
预期:
- Linux
- con(应该是动态设置属性的名称)
我明白了:
- Linux
- 条件(属性值的名称(未绑定
self.condition))
但我希望 f.con.__name__ 返回属性的名称 (con) 而不是分配给它的未绑定函数的名称 (condition)。
有人可以向我解释为什么会出现这种行为,我该如何解决?
谢谢。
【问题讨论】:
标签: python class setattribute setattr dynamic-function