我在使用Python decorators时遇到了一些困难,我认为这与我将一个类作为参数传递给函数装饰器有关,而被修饰的函数是被传递的类的一个方法。在
对于这个问题,我没有比这更清楚的解释了,所以希望一些代码可以帮助:
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)
...
我不认为@accepts
的定义很重要,但我还是把它放在这里以防万一:
我得到以下错误:
File "raytracerBase.py", line 41, in <module>
class Vector:
File "raytracerBase.py", line 42, in Vector
@accepts(Vector, float, float, float)
NameError: name 'Vector' is not defined
我想我的评论解释了我的想法:这个类还没有被定义(因为,我正在定义它),因此我不能通过它。在
是否有一个整洁的解决方案不是:
assert isinstance(self, Vector), "Something is wrong... very wrong..."
我知道我的类型检查超出了被认为是必要的,但我想知道如何解决这类问题。在
编辑:我还知道@accepts
实际上并不是有效的Python。但是,这是我打算实现的代码的大纲。在
简单的回答是不,在定义完类之前,不能像那样引用类。在
类型检查是Python开发团队目前正在积极讨论的一个主题,在某种程度上,function annotations是前进的方向:PEP 484描述了Guido在实现它时想要采取的方向。在
在该PEP中,转发引用proposed的解决方法是只使用字符串:
相关问题 更多 >
编程相关推荐