0

I am pretty new to python scripts in linux and executing them in the terminal. I am trying to debug a few scripts that interact with each other, but i don't understand how to access certain parts of the script in the command line. Below is an example test script I'm practicing with.

The file is called:

test.py

The script is:

class testClass():

    def __init__(self, test):

        self.test = test

    def testing():

        print "this wont print"


def testing2():

   print "but this works"

In the terminal if I go to the folder where the file is located and try to print the testing() function

python -c 'import test; print test.testClass.testing()'

I get an error saying

Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: unbound method testing() must be called with testClass instance  as first argument (got nothing instead)

But if i try to print the testing2() function

python -c 'import test; print test.testing2()'

It will print "but this works"

How would i go about executing the testing() function to make it print. I've tried putting various arguments in there but nothing works.

Thanks

Michael Scarpa
  • 121
  • 2
  • 13
  • 1
    `testing2()` is a function, whereas `testClass.testing()` is a **method**. You need to first create an instance of `testClass` and then call `testing()` on that instance. But in order for that to work, you need to make `testing()` take `self` as the first argument (or define it as a static method, if that's what you actually wanted). – Lukas Graf Apr 02 '15 at 15:32
  • Also, there's no reason to use the very limited `python -c '...'`. Instead just start an [interactive Python interpreter](https://docs.python.org/2/tutorial/interpreter.html#interactive-mode) by running `python` on your shell (from the same working directory), and enter the same statements, and enjoy the benefits of [interactively inspecting](https://docs.python.org/2/tutorial/introduction.html#using-python-as-a-calculator) your code. – Lukas Graf Apr 02 '15 at 15:48
  • Yea i didn't even know that was a thing haha. Will use that from now on – Michael Scarpa Apr 02 '15 at 15:52

1 Answers1

1

Your class should be:

class testClass():
    def __init__(self, test):
        self.test = test

    def testing(self):
        print "this wont print"

The method needs to be called with an instance of testClass:

test.testClass("abc").testing()

Where "abc" represents your test __init__ argument. Or:

t = test.testClass("abc")
test.testClass.testing(t)

As a shell command:

python -c 'import test; print test.testClass("abc").testing()'

See Difference between a method and a function and What is the purpose of self? for more information.

Community
  • 1
  • 1
matsjoyce
  • 5,744
  • 6
  • 31
  • 38