【发布时间】:2019-06-27 10:36:11
【问题描述】:
我有一个简单的类,我想在其中生成基于继承的类字段的方法:
class Parent:
def __init__(self, *args, **kwargs):
self.fields = getattr(self, 'TOGGLEABLE')
self.generate_methods()
def _toggle(self, instance):
print(self, instance) # Prints correctly
# Here I need to have the caller method, which is:
# toggle_following()
def generate_methods(self):
for field_name in self.fields:
setattr(self, f'toggle_{field_name}', self._toggle)
class Child(Parent):
following = ['a', 'b', 'c']
TOGGLEABLE = ('following',)
此时,Child中已经成功生成了一个toggle_following函数。
然后我用一个参数调用它:
>>> child = Child()
>>> child.toggle_following('b')
<__main__.Child object at 0x104d21b70> b
它会在print 语句中打印出预期的结果。
但我需要在我的通用 _toggle 函数中接收呼叫者姓名 toggle_following。
我尝试过使用inspect 模块,但它在功能检查方面似乎有不同的目的。
【问题讨论】:
-
发布您的
toggle_following声明并描述其目的 -
@RomanPerekhrest 我认为这是minimal reproducible example 的一个很好的例子。实际的切换功能与问题无关,只会使事情复杂化。
标签: python python-3.x metaprogramming getattr setattr