【发布时间】:2012-08-20 14:25:41
【问题描述】:
我在一个模块中有以下装饰器:
class CachedProperty(object):
"""Decorator that lazy-loads the value of a property.
The first time the property is accessed, the original property function is
executed. The value it returns is set as the new value of that instance's
property, replacing the original method.
"""
def __init__(self, wrapped):
self.wrapped = wrapped
try:
self.__doc__ = wrapped.__doc__
except:
pass
def __get__(self, instance, instance_type=None):
if instance is None:
return self
value = self.wrapped(instance)
setattr(instance, self.wrapped.__name__, value)
return value
我想像这样从模块中导入这个装饰器和其他东西:
from clang.cindex import *
但我无法以这种方式导入单个装饰器,如果我这样做,它就可以工作:
from clang.cindex import CachedProperty
那么我可以使用@CachedProperty。
为什么我不能通过* 导入这个类,而我可以导入其他类?
【问题讨论】:
-
import *往往会引起人们的不满,因为它会造成名称冲突,我很好奇你会遇到什么错误? -
在使用 @CachedProperty 装饰某些属性时,我收到一条错误消息,提示未定义 CachedProperty。
-
我知道它不受欢迎,但我仍然想知道它为什么不起作用。没有发生名称冲突。
-
不想侮辱你的智力,但你确定
CachedProperty是在你导入的模块中定义的吗?clange.cindex是子包吗?如果是这样,您必须在模块中设置__all__变量以告诉 python 在您执行from _ import *时要导入哪些名称
标签: python properties import decorator