如何将文件名作为 Class 变量传递?
How to pass a filename as a Class variable?
我正在尝试构建一个 Tkinter 应用程序,它允许您加载文档然后分析它们。我必须承认我仍然在掌握面向对象的编程,如果这是一个简单的答案,我深表歉意。
我构建了这个 Class 来保存文件路径变量以供应用程序的其余部分使用。
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
但是每次我尝试通过以下内容时:
b = ‘CV_test.txt’
Inputs.cv(b)
我收到以下错误。
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'
是否无法将文件路径作为 Class 变量传递?
补充问题:这种方法能让我以后在其他 类 中调用这些变量吗?
Class 变量定义在 __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 !!
输出:
JS_Test.txt
CV_Test.txt
None
我正在尝试构建一个 Tkinter 应用程序,它允许您加载文档然后分析它们。我必须承认我仍然在掌握面向对象的编程,如果这是一个简单的答案,我深表歉意。
我构建了这个 Class 来保存文件路径变量以供应用程序的其余部分使用。
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
但是每次我尝试通过以下内容时:
b = ‘CV_test.txt’
Inputs.cv(b)
我收到以下错误。
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'
是否无法将文件路径作为 Class 变量传递?
补充问题:这种方法能让我以后在其他 类 中调用这些变量吗?
Class 变量定义在 __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 !!
输出:
JS_Test.txt
CV_Test.txt
None