如何在python __init__中处理缺少的args?

Lys*_*ion 1 python constructor

在多线程实现中,我需要生成大量指令,然后将它们传递给单个处理线程.这是我的自定义指令类:

class instruction:
    priority = 10
    action = ""
    data = ""
    condition = ""
    target = ""

    ### constructor(s) declaration
    def __init__(self,priority=10,target="",action="",data="",condition=""):
        self.priority = priority
        self.target = target
        self.action = action
        self.data = data
        self.condition = condition
Run Code Online (Sandbox Code Playgroud)

我将不得不调用不同类型的指令,因此定义的参数可能不同.它总是缺少一个参数,如没有目标,没有动作等.

和当前的构造函数一样,如果我在没有目标的情况下调用它,我会得到:

i = instruction(priority_value,action_value,data_value,condition_value)
print(i.priority)
>>> priority_value
print(i.target)
>>> action_value
print(i.action)
>>> data_value
print(i.target)
>>> data_value
print(i.data)
>>> condition_value
print(i.condition)
>>> #nothing to see here, move along!
Run Code Online (Sandbox Code Playgroud)

我知道我可以定义自定义构造函数,比如

@classmethod
def noTarget(priority=10,action=0,data="",condition=""):
return instruction(priority,"",action,data,condition)
Run Code Online (Sandbox Code Playgroud)

然后将其称为 i=instruction.noTarget(priority_value,action_value,data_value,condition_value)

但是,还有其他方法吗?
如果是这样,你能详细说明一下吗?谢谢!

对不起,如果我误用或拼写错误的单词,英语不是我的母语.

Mar*_*ers 6

你在你的函数定义的所有参数都是可选的,因为他们被指定为默认参数,所以你不要在所有的值传递.

当调用功能,只是命名你的论点想传递; 这些被称为关键字参数:

instruction(priority=priority_value, action=action_value,
            data=data_value, condition=condition_value)
Run Code Online (Sandbox Code Playgroud)

在呼叫中使用关键字参数时,顺序无关紧要,您可以自由地混合它们.

另请参阅Python教程的关键字参数部分.