Jad*_*ine 7 python methods class sys
所以我在Python脚本中编写了一些类,如:
#!/usr/bin/python
import sys
import csv
filepath = sys.argv[1]
class test(object):
def __init__(self, filepath):
self.filepath = filepath
def method(self):
list = []
with open(self.filepath, "r") as table:
reader = csv.reader(table, delimiter="\t")
for line in reader:
list.append[line]
Run Code Online (Sandbox Code Playgroud)
如果我从命令行调用此脚本,我怎么能调用方法?所以通常我输入:$ python test.py test_file现在我只需要知道如何访问名为"method"的类函数.
您将创建该类的实例,然后调用该方法:
test_instance = test(filepath)
test_instance.method()
Run Code Online (Sandbox Code Playgroud)
请注意,在 Python 中,您不必创建类来运行代码。您可以在这里使用一个简单的函数:
import sys
import csv
def read_csv(filepath):
list = []
with open(self.filepath, "r") as table:
reader = csv.reader(table, delimiter="\t")
for line in reader:
list.append[line]
if __name__ == '__main__':
read_csv(sys.argv[1])
Run Code Online (Sandbox Code Playgroud)
我将函数调用移至守卫,__main__
以便您还可以将脚本用作模块并导入该read_csv()
函数以在其他地方使用。
归档时间: |
|
查看次数: |
19764 次 |
最近记录: |