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

Python中获取类属性时报错:'str' object is not callable

排查解决:TypeError: 'str' object is not callable

先来看你的代码结构:

dialogs.py 代码

import wx
import wx.adv
class Dialogs():
    def __init__(self):
        self._InputValue = ""
    def DialogInput(self, message, title, defaultvalue=""):
        dlg = wx.TextEntryDialog(None, message, title)
        if dlg.ShowModal() == wx.ID_OK:
            print("User enetered: {}".format(dlg.GetValue()))
            self._InputValue = dlg.GetValue()
        dlg.Destroy()
        return self
    @property
    def InputValue(self):
        return self._InputValue

dbinit.py 代码

from dialogs import Dialogs
...

错误原因分析

这个报错的核心原因是你把用@property装饰的属性当成方法来调用了。

@property装饰器的作用是把一个方法伪装成实例属性,让你可以像访问普通变量一样获取它的返回值,而不需要加括号调用。你的InputValue返回的是字符串类型的self._InputValue,如果在dbinit.py里你写了类似这样的代码:

dialog = Dialogs()
dialog.DialogInput("Test", "Title").InputValue()  # 这里加了括号!

相当于你拿到字符串后试图调用它("some_str"()),这自然会触发TypeError: 'str' object is not callable。

解决方案

有两种常见的修复方式:

方式1:正确访问属性(推荐)

直接去掉调用时的括号,像访问普通变量一样获取值:

from dialogs import Dialogs

# 普通写法
d = Dialogs()
d.DialogInput("Enter your content", "Input Dialog")
user_input = d.InputValue  # 没有括号
print(user_input)

# 链式调用写法(因为DialogInput返回self)
user_input = d.DialogInput("Enter content", "Input").InputValue  # 同样没有括号

方式2:改成普通方法(如果习惯方法调用)

如果你更习惯用xxx()的方式获取值,可以去掉@property装饰器,把它改成普通的getter方法:

# 修改dialogs.py中的代码
class Dialogs():
    # ... 其他代码不变 ...
    
    # 去掉@property,改成普通方法
    def GetInputValue(self):
        return self._InputValue

然后在dbinit.py里这样调用:

d = Dialogs()
d.DialogInput("Test", "Title")
user_input = d.GetInputValue()  # 加括号调用方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:40:28