【问题标题】:Python : how to use another method's returning value in another method?Python:如何在另一个方法中使用另一个方法的返回值?
【发布时间】:2018-08-09 13:15:54
【问题描述】:

我想要做的是从 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())

而且错误是这样出现的

Traceback(最近一次调用最后一次): 文件“C:\Users\mg\Desktop\Tubuc\openAPI\test9.py”,第 16 行,在 t.line_count(abcd(fname)) NameError: name 'abcd' 没有定义

【问题讨论】:

  • 错误是什么?请在问题中包含完整的回溯。
  • 您没有提供完整的文件路径,所以我认为“错误”与不知道在哪里查找文件有关。

标签: python methods


【解决方案1】:

只看函数:

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())

【讨论】:

    【解决方案2】:

    abcd 是一个实例方法,所以你必须从你的类的实例中调用它

    t = Test()
    t.line_cont(t.abcd())
    

    您的abcd 方法在定义之前也使用了变量a,因此您可以将其更改为

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

    【讨论】:

      【解决方案3】:

      看起来你想要从你的 abcd 方法中得到什么通常是在一个 init 中处理的。您可以在实例化 Test 对象时设置文件名。然后你可以调用行数。您的 line_count 方法还应指定如何以读取模式打开文件“r”。

      class Test():
          def __init__(self, file_name):
              self._file_name = file_name
      
      
          def line_count(self):
              with open(self._file_name, 'r') as f:
                  for i, l in enumerate(f):
                      pass
              return i + 1
              print(i + 1)
      
      t = Test('ICB164000395.txt')
      t.line_count()
      

      【讨论】:

        猜你喜欢
        • 2017-10-01
        • 2021-07-07
        • 1970-01-01
        • 2014-06-23
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多