Home > Enterprise >  How to pass a filename as a Class variable?
How to pass a filename as a Class variable?

Time:12-12

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?

CodePudding user response:

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
  • Related