gpt4 book ai didi

python : how to use another method's returning value in another method?

转载 作者:行者123 更新时间:2023-12-01 09:09:38 25 4
gpt4 key购买 nike

我想做的是从 abcd 方法获取返回值,并使用该值作为 fname 的替换,并且错误继续发生。

如何修复这个错误?

ICB164000395.txt 有四行。我想要 line_count 打印出 4(文本文件中的行数)

class Test():
def abcd(self):
self.a = a
a = 'ICB164000395.txt'
return a


def line_count(self, fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(i + 1)

t = Test()
t.line_count(abcd())

错误如下所示

回溯(最近一次调用最后一次): 文件“C:\Users\mg\Desktop\Tubuc\openAPI\test9.py”,第 16 行,位于 t.line_count(abcd(fname))NameError:名称“abcd”未定义

最佳答案

只看函数:

def abcd(self):
self.a = a
a = 'ICB164000395.txt'
return a

我猜您在 self.a = a 处遇到错误。因为 a 尚未定义。也没有传入。

我认为你想要的是:

class Test():
def abcd(self):
a = 'ICB164000395.txt' # you'll need to correct the path to this file
return a


def line_count(self, fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(i + 1)

t = Test()
t.line_count(t.abcd())

关于 python : how to use another method's returning value in another method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51768068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com