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

Python类方法中字符串参数未被识别问题求助

问题分析与解决

嘿,我一眼就发现问题所在了!你的代码里的displayCount方法存在作用域错误,导致字符串参数没被正确识别。

问题根源

在CurrenciPair类的displayCount方法中,你直接使用了market_pair变量,但这个变量并没有在方法的局部作用域中定义——它是类实例的属性,必须通过self.前缀来访问。

错误代码片段

def displayCount(self):
    histo = market_pair
    print(market_pair)

这段代码会触发NameError: name 'market_pair' is not defined,因为Python找不到这个变量的定义。

修正后的完整代码

# tst.py文件内容
class CurrenciPair():
    def __init__(self, market_pair):
        self.market_pair = market_pair
    def displayCount(self):
        histo = self.market_pair  # 使用self.访问实例属性
        print(self.market_pair)   # 同样需要self.

def reco(market_pair):
    print(market_pair)
    emp = CurrenciPair(market_pair)
    emp.displayCount()

解释

在类的__init__方法中,你已经把传入的market_pair赋值给了self.market_pair,这意味着每个CurrenciPair实例都拥有自己的market_pair属性。当你在类的其他方法中需要访问这个属性时,必须通过self.来引用,这样Python才能定位到实例的属性值。

运行结果

修正后执行test.py,会输出:

TEST
TEST

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:45:43