我如何通过自我传递参数

时间:2017-01-10 07:28:34

标签: python-2.7

def read_contents(self,filename):
    with open(filename,'r') as f:
        lines=f.read().splitlines()
        print lines

s=read_contents('input.txt')

当试图运行这个程序时,会抛出错误,因为需要两个参数并且self需要作为参数之一出现(这是更大代码的一部分) 如何将filename作为参数传递而不会出现错误

1 个答案:

答案 0 :(得分:1)

您必须在课程中使用它:

class Test:
    def read_contents(self, filename):
        with open(filename, 'r') as f:
            lines = f.read().splitlines()
            print lines

test = Test()
s = test.read_contents('input.txt')

或删除自我:

def read_contents(filename):
    with open(filename, 'r') as f:
        lines = f.read().splitlines()
        print lines

s = read_contents('input.txt')