如何在python3中正确使用@property decorator?

2024-04-29 14:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

^{pr2}$

在最后一行(print方法)我得到异常:

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

我的代码有什么问题?在


Tags: 方法脚本objectiswithnotfunctionproperty
1条回答
网友
1楼 · 发布于 2024-04-29 14:26:34

@property只对方法有效,对函数无效。在

get_from_store不是一个方法,而是一个函数。一个property对象充当descriptor object,描述符只在类和实例的上下文中工作。在

在您的例子中,没有必要将get_from_store作为属性。删除@property修饰符,然后像函数一样使用它:

athletes = get_from_store()

否则,您无法使顶级函数的行为类似于属性。在

相关问题 更多 >