You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类函数报错:'str' object is not callable 求助

这个错误的根源很明确——你把用@property装饰的属性当成方法来调用了!

问题分析

@property装饰器的作用是把一个方法转换成只读属性,当你用@property修饰_build_url后,self._build_url直接返回的是字符串结果,而不是可调用的方法。这时候你加了括号self._build_url(),就相当于尝试调用一个字符串对象,自然会抛出TypeError: 'str' object is not callable。

两种解决办法

方案1:移除@property装饰器,把_build_url作为普通方法使用

如果希望它是一个需要主动调用的方法,直接去掉@property即可:

class Page:
    def __init__(self, pid, cur_id, url=None, proxy=None):
        self.pid = pid
        self.cur_id = cur_id
        if url is None:
            self.url = self._build_url()  # 保留括号调用方法
        else:
            self.url = url
        self.content = get_page_content(self.url, proxy)
        self.crawl_date = datetime.now()

    # 移除@property,恢复为普通方法
    def _build_url(self):
        my_url = root + self.pid
        return my_url

方案2:保留@property,但访问时去掉括号

如果确实想把它作为属性来用,那么在__init__里直接访问属性即可,不需要加括号:

class Page:
    def __init__(self, pid, cur_id, url=None, proxy=None):
        self.pid = pid
        self.cur_id = cur_id
        if url is None:
            self.url = self._build_url  # 去掉括号,直接访问属性
        else:
            self.url = url
        self.content = get_page_content(self.url, proxy)
        self.crawl_date = datetime.now()

    @property
    def _build_url(self):
        my_url = root + self.pid
        return my_url

额外小建议

一般来说,以下划线开头的标识符如果是属性,命名上可以更贴合属性语义,比如改成_built_url会更直观,但这只是代码风格问题,不影响功能运行。

内容的提问来源于stack exchange,提问作者Maeaex1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:25:54