【问题标题】:'str' object is not callable in python class function'str' 对象在 python 类函数中不可调用
【发布时间】:2019-07-30 13:16:12
【问题描述】:

我正在构建一个具有Page class 的网络爬虫。但是,在将属性 url 分配给 Page class 时,我收到以下错误消息。

TypeError: 'str' 对象不可调用

在我的代码下面找到:

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

有什么建议吗?

编辑: 完整追溯:

> Traceback (most recent call last):   File "C:\Program
> Files\JetBrains\PyCharm Community Edition
> 2019.1.3\helpers\pydev\pydevd.py", line 2060, in <module>
>     main()   File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.3\helpers\pydev\pydevd.py", line 2054, in main
>     globals = debugger.run(setup['file'], None, None, is_module)   File "C:\Program Files\JetBrains\PyCharm Community Edition
> 2019.1.3\helpers\pydev\pydevd.py", line 1405, in run
>     return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)   File "C:\Program Files\JetBrains\PyCharm Community
> Edition 2019.1.3\helpers\pydev\pydevd.py", line 1412, in _exec
>     pydev_imports.execfile(file, globals, locals)  # execute the script   File "C:\Program Files\JetBrains\PyCharm Community Edition
> 2019.1.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
>     exec(compile(contents+"\n", file, 'exec'), glob, loc)   File "C:/single_offers.py",
> line 146, in <module>
>     main()   File "C:/single_offers.py",
> line 68, in main
>     p = Page(id, cur_id, proxy=proxy)   File "C:/single_offers.py",
> line 109, in __init__
>     self.url = self._build_url() TypeError: 'str' object is not callable
> 
> Process finished with exit code 1

【问题讨论】:

  • 您能否提供完整的错误堆栈跟踪,而不仅仅是最后一行?

标签: python string class


【解决方案1】:

您已将_build_url 声明为一个属性。因此,您只使用属性名称而不是调用它来访问它:

self.url = self._build_url

【讨论】:

    【解决方案2】:

    您将_build_url 设为属性,因此self._build_url 获得了没有调用括号的str,但您添加了括号以使其成为self.url = self._build_url()。所以你试图调用结果字符串。要么删除 @property 装饰器以使其成为普通方法,要么在使用点删除调用括号以使用该属性而不调用它。

    【讨论】:

      【解决方案3】:

      你把_build_url 变成了@property。因此,当您要调用此方法时,不应使用self._build_url(),而应使用self._build_url(不带括号)。

      【讨论】:

        猜你喜欢
        • 2013-05-05
        • 2023-02-01
        • 1970-01-01
        • 2012-12-09
        • 2015-06-07
        • 2019-07-10
        • 2020-09-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多