类方法作为变量分配函数的包装器

时间:2019-05-28 21:55:38

标签: python class methods wrapper

我正在尝试了解python类和函数包装器/装饰器,目前,某些功能并没有达到我希望并发现有用的功能。

看看这个(人为)例子:

class Pet:

    def __init__(self, animal):
        self.animal = animal

    def setAction(self):
        def bark(times):
            """Lets the animal bark, because it's a dog. Args: number of times."""
            print('woof ' * times)
        def jump(height):
            """Lets the animal jump, because I don't know what it is. Args: how high."""
            print('jumps {:} cm high!'.format(height))
        self.doAction = bark if self.animal == 'dog' else jump

bunny = Pet('rabbit')
bunny.setAction()
bunny.doAction(20)         #correctly outputs 'jumps 20 cm high!'

fiddo = Pet('dog')
fiddo.setAction()
fiddo.doAction(2)          #correctly outputs 'woof woof'

尽管这一切正常,但并不理想。首先,仔细检查代码,很容易错过在setAction方法的最后一行(特别是)中将函数附加到对象的情况。随着班级的扩大。其次,让类的使用者在调用之前检查doAction是否已设置。第三,在barkjump中都需要实施任何其他错误检查。

为了改进,我添加了一种方法doAction2。它会进行一些错误检查,但除此之外,所有参数都应直接传递到self.doAction

class Pet:

    def __init__(self, animal):
        (...)

    def setAction(self):
        (...)

    def doAction2(self, *args, **kwargs):
        (...error checking etc...)
        self.doAction(*args, **kwargs)              

这里的问题是,尽管调用bunny.doAction2确实可行,但至少有一个问题(我知道):向消费者提供的所有信息都消失了,因为该文档字符串未传递。有办法保留吗?另外,还有其他陷阱吗?

非常感谢!

0 个答案:

没有答案