小编the*_*mms的帖子

允许python装饰器在传递的类中使用时将类作为参数

我在Python装饰器方面遇到了一些困难,我认为这与我将一个类作为参数传递给函数装饰器的事实有关,当被装饰的函数是传递类的方法时.

我没有比这更清楚的解释问题,所以希望一些代码可以帮助:

from typeChecking import *

class Vector:
    @accepts(Vector, float, float, float) #Vector hasn't been defined yet... In c++ I could forward declare...
    def __init__(self, x, y, z):
        self._x = float(x)
        self._y = float(y)
        self._z = float(z)
    ...
Run Code Online (Sandbox Code Playgroud)

我不认为这个定义@accepts很重要,但我会留在这里以防万一:

def accepts(*types):
    def check_accepts(f):
        assert len(types) == f.func_code.co_argcount
        def new_f(*args, **kwds):
            for (a, t) in zip(args, types):
                assert isinstance(a, t), \
                       "arg %r does not match %s" % (a,t)
            return f(*args, **kwds)
        new_f.func_name = f.func_name
        return new_f
    return check_accepts …
Run Code Online (Sandbox Code Playgroud)

python typechecking python-decorators

4
推荐指数
1
解决办法
201
查看次数

标签 统计

python ×1

python-decorators ×1

typechecking ×1