如何在python 3中正确使用@property装饰器?

时间:2014-08-23 13:41:46

标签: python python-3.x properties decorator python-decorators

我在@property脚本中使用athleteModel.py注释了方法:

@property
def get_from_store():
    with open(athleteFilePath,'rb') as pickleFile:
        athleteMap = pickle.load(pickleFile)
    print('Loaded athleteMap ',athleteMap)
    return athleteMap

我在另一个脚本中使用此方法:

from athleteModel import get_from_store

athletes = get_from_store
print(yate.u_list(athletes[athName].sortedTimes))

在最后一行(print方法)我得到例外:

TypeError: 'function' object is not subscriptable 
      args = ("'function' object is not subscriptable",) 
      with_traceback = <built-in method with_traceback of TypeError object>

我的代码有什么问题?

1 个答案:

答案 0 :(得分:2)

@property仅适用于方法,而不适用于函数。

get_from_store不是一种方法,它是一种功能。 property对象充当descriptor object,描述符仅适用于类和实例的上下文。

在你的情况下,确实没有必要让get_from_store属性。删除@property装饰器,只需使用它就像一个函数:

athletes = get_from_store()

否则,您无法将顶级函数视为属性。