1

I am trying to build a Tkinter app which allows you load documents and then analyse them. I must admit I am still getting to grips with object-oriented programming, so apologies if this is a simple answer.

I have built this Class to hold the filepath variables for the rest of the app to use.

class Inputs:
    def __init__(self, CV, JS):
        self.CV = CV
        self.JS = JS

    def cv(self, input):
        self.CV = input

    def js(self, input):
        self.JS = input

However everytime I try to pass the following:

b = ‘CV_test.txt’
Inputs.cv(b)

I get the following error.

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3319, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-5-f21fa013f9ae>", line 1, in <module>
    Inputs.cv(b)
TypeError: cv() missing 1 required positional argument: 'input'

Is it not possible to pass a filepath as a Class variable?

Supplementary question: Will this approach enable me to call on these variables in other classes at a later date?

Tom_Scott
  • 95
  • 7
  • 1
    do you need `Inputs.CV("CV_Test.txt")`? I would not use `input` as a variable name, btw. Is `inputs` a object you have already initialized? – nikeros Dec 11 '21 at 20:48
  • 1
    When you access `class` `methods` directly you don't create an instance of the class so `self` is not passed. Make it a `@staticmethod` – Pedro Maia Dec 11 '21 at 20:49
  • 1
    You defined instance variables, not class variables. Related: https://stackoverflow.com/questions/8959097/what-is-the-difference-between-class-and-instance-variables – Maurice Meyer Dec 11 '21 at 21:01

1 Answers1

1

Class variables are defined outside of __init__:

class Inputs:
    CV = None
    JS = None
    SELF_JS = None

    def cv(self, inp):
        Inputs.CV = inp

    def js(self, inp):
        Inputs.JS = inp

    def self_js(self, inp):
        # this dont work...
        self.SELF_JS = inp


Inputs.CV = 'CV_Test.txt'

my_inputs1 = Inputs()
my_inputs1.js('JS_Test.txt')
my_inputs1.self_js('SELF_Test.txt')
my_inputs2 = Inputs()

print(my_inputs2.JS)
print(my_inputs2.CV)
print(my_inputs2.SELF_JS)  # Not available in my_inputs2 !!

Out:

JS_Test.txt
CV_Test.txt
None
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47