so I wrote some class in a Python script like:
#!/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]
If I call this script from the command line, how am I able to call method? so usually I enter: $ python test.py test_file Now I just need to know how to access the class function called "method".
To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!
Once a function is created in Python, we can call it by writing function_name() itself or another function/ nested function. Following is the syntax for calling a function. Syntax: def function_name():
To run the Python Shell, open the command prompt or power shell on Windows and terminal window on mac, write python and press enter. A Python Prompt comprising of three greater-than symbols >>> appears, as shown below. Now, you can enter a single statement and get the result.
You'd create an instance of the class, then call the method:
test_instance = test(filepath)
test_instance.method()
Note that in Python you don't have to create classes just to run code. You could just use a simple function here:
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])
where I moved the function call to a __main__
guard so that you can also use the script as a module and import the read_csv()
function for use elsewhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With