python - 从命令行调用 Python 类方法

标签 python class methods 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]

如果我从命令行调用这个脚本,我如何调用方法? 所以通常我输入:$ python test.py test_file 现在我只需要知道如何访问名为“方法”的类函数。

最佳答案

您将创建该类的一个实例,然后调用该方法:

test_instance = test(filepath)
test_instance.method()

请注意,在 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])

我将函数调用移至 __main__ 守卫,以便您可以将脚本用作模块并导入 read_csv() 在别处使用的功能。

关于python - 从命令行调用 Python 类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31380347/

相关文章:

python - 使用 skimage.color.rgb2lab() 将 RGB 三元组转换为 LAB 三元组

python - 如何使用django项目上传csv文件

python - 属性错误: type object 'projectile' has no attribute 'dir'

java - 构造函数中可重写的方法调用

arrays - 给定一个 arr[i] = i-1 的数组,用下面的方法,输出是什么?

python - 推荐的 Python 加密模块?

python - 选择要以编程方式访问的属性

c++ - 类模板,预期的构造函数,析构函数

c++ - 具有指定基类的类声明

php - 从另一个类宽度 '$this' 调用类的静态方法