简体   繁体   English

如何处理python __init__中缺少的参数?

[英]How to handle missing args in python __init__?

In a multi-threaded implementation, i need to generate lots of instructions, then pass them to the single processing thread. 在多线程实现中,我需要生成大量指令,然后将它们传递给单个处理线程。 Here is my custom Instruction class: 这是我的自定义指令类:

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

I will have to call different kinds of instructions, thus the defined parameters may differ. 我将不得不调用不同种类的指令,因此定义的参数可能会有所不同。 It will always be one parameter missing, like no target, no action, etc. 它始终是一个缺少参数,例如没有目标,没有动作等。

As is the current constructor, if i call it without target, i'll get that: 与当前的构造函数一样,如果我在没有目标的情况下调用它,则会得到:

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!

I know i can define custom constructors, like 我知道我可以定义自定义构造函数,例如

@classmethod
def noTarget(priority=10,action=0,data="",condition=""):
return instruction(priority,"",action,data,condition)

and then call it as i=instruction.noTarget(priority_value,action_value,data_value,condition_value) 然后将其称为i=instruction.noTarget(priority_value,action_value,data_value,condition_value)

But, is there other ways to do that? 但是,还有其他方法可以做到吗?
If so, could you please detail these? 如果是这样,请您详细说明一下? Thanks! 谢谢!

Sorry if i mis-used or mis-spelled some words, English isn't my native language. 抱歉,如果我误用或拼错了一些单词,英语不是我的母语。

All your parameters in your function definition are optional as they are specified as default parameters, so you don't have to pass in values for all. 你在你的函数定义的所有参数都是可选的,因为他们被指定为默认参数,所以你不必在所有的值传递。

When calling the function, just name the arguments you do want to pass in; 当调用功能,只是名称 想传递的参数; these are called keyword arguments: 这些称为关键字参数:

instruction(priority=priority_value, action=action_value,
            data=data_value, condition=condition_value)

When using keyword arguments in a call, the order doesn't matter, you can mix them up freely. 在通话中使用关键字参数时,顺序无关紧要,您可以自由地将它们混合在一起。

Also see the Keyword Arguments section of the Python tutorial. 另请参阅Python教程的“ 关键字参数”部分

Pass keyword arguments. 传递关键字参数。

i = instruction(priority=priority_value,
                action=action_value,
                data=data_value,
                condition=condition_value)

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

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