简体   繁体   English

如何在python class中添加可选的arguments?

[英]How to add optional arguments in a python class?

I am trying to call different functions based on the value for rb_selection, calling func1 if rb_selection value is 0 and calling func2 if rb_selection value is 1. Both functions take a different set of arguments.我试图根据 rb_selection 的值调用不同的函数,如果 rb_selection 值为 0 则调用 func1,如果 rb_selection 值为 1 则调用 func2。这两个函数采用不同的一组 arguments。

I do not need folder argument(func2 values) when I call func1 and similarly I do not need batch, term arguments(func1 values) when I call func2当我调用 func1 时我不需要文件夹参数(func2 值)同样当我调用 func2 时我不需要批处理,术语参数(func1 值)

It throws me the below error when I try to call the second function, as the values for batch, term are not passed.当我尝试调用第二个 function 时,它会抛出以下错误,因为 batch、term 的值未传递。

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Himajak\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "<ipython-input-13-02b5f954b815>", line 122, in tb_click
    ThreadedTask(self.queue,self.batch_name,self.term_name,self.course,self.rb_selection,self.folder).start()
AttributeError: 'GUI' object has no attribute 'batch_name'

Code looks similar to this:代码看起来类似于:

class class1():

    def def1(self):

        self.queue = queue.Queue()
        ThreadedTask(self.queue,self.rb_selection,self.batch_name,self.folder).start()
        #self.master.after(10, self.process_queue)


class class2():

    def __init__(self, queue,rb_selection, batch_name ,term_name, folder):
        threading.Thread.__init__(self)
        self.queue = queue
        self.rb_selection = rb_selection
        self.batch = batch_name
        self.term = term_name
        self.folder = folder


    def func1(self,batch,term):
        time.sleep(5)
        print("Fucntion 1 reached")
        print(self.batch,self.term)


    def func2(self,folder):
        time.sleep(5)
        print("Function 2 reached")
        print(self.folder)

    def run(self):
        time.sleep(0) # Simulate long running process

        if self.rb_selection == '0':
            self.func1(self.batch,self.term)
        elif self.rb_selection == '1':
            self.func2(self.folder)

        self.queue.put("Task finished")

Please suggest on how to resolve this issue, thanks in advance!请建议如何解决此问题,在此先感谢!

There is no concept of optional arguments, you can give default value when creating the function like没有optional arguments的概念,可以在创建function时给定默认值like

def __init__(self, queue,rb_selection ,term_name, folder, batch_name="default batch name"):

So that you need not pass batch_name while creating the Instance.这样您就无需在创建实例时传递batch_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM