使用setattr()时获取真实的调用方方法名称

时间:2019-06-27 10:36:11

标签: python python-3.x metaprogramming getattr setattr

我有一个简单的类,我想在其中基于继承的类字段生成方法:

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',)

此刻,toggle_following中成功生成了一个Child函数。

然后我用一个参数调用它:

>>> child = Child()
>>> child.toggle_following('b')
<__main__.Child object at 0x104d21b70> b

它会在print语句中打印出预期结果。

但是我需要在通用toggle_following函数中接收呼叫者姓名_toggle

我尝试使用inspect模块,但似乎在功能检查方面有不同的用途。

2 个答案:

答案 0 :(得分:2)

也许这太骇人听闻了,也许有一种更优雅(即专用)的方法来实现这一目标,但是:

您可以创建一个包装函数,将func_name传递给内部_toggle func:

class Parent:
    def __init__(self, *args, **kwargs):
        self.fields = getattr(self, 'TOGGLEABLE')
        self.generate_methods()

    def _toggle(self, instance, func_name):
        print(self, instance)  # Prints correctly
        print(func_name)

    def generate_methods(self):
        for field_name in self.fields:
            func_name = 'toggle_{}'.format(field_name)  # I don't have python 3.7 on this computer :P
            setattr(self, func_name, lambda instance: self._toggle(instance, func_name))


class Child(Parent):
    following = ['a', 'b', 'c']

    TOGGLEABLE = ('following',)


child = Child()
child.toggle_following('b')

输出:

<__main__.Child object at 0x7fbe566c0748> b
toggle_following

答案 1 :(得分:1)

解决同一问题的另一种方法是通过以下方式使用__getattr__

class Parent:
    def _toggle(self, instance, func_name):
        print(self, instance)  # Prints correctly
        print(func_name)

    def __getattr__(self, attr):

        if not attr.startswith("toggle_"):
            raise AttributeError("Attribute {} not found".format(attr))

        tmp = attr.replace("toggle_", "")
        if tmp not in self.TOGGLEABLE:
            raise AttributeError(
                "You cannot toggle the untoggleable {}".format(attr)
            )

        return lambda x: self._toggle(x, attr)


class Child(Parent):
    following = ['a', 'b', 'c']
    TOGGLEABLE = ('following',)


child = Child()
# This can toggle
child.toggle_following('b')

# This cannot toggle
child.toggle_something('b')

产生:

(<__main__.Child instance at 0x107a0e290>, 'b')
toggle_following

Traceback (most recent call last):
  File "/Users/urban/tmp/test.py", line 26, in <module>
    child.toggle_something('b')
  File "/Users/urban/tmp/test.py", line 13, in __getattr__
    raise AttributeError("You cannot toggle the untoggleable {}".format(attr))
AttributeError: You cannot toggle the untoggleable toggle_something