python 类初始化器中的可选参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15535655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:20:57  来源:igfitidea点击:

optional arguments in initializer of python class

pythonoopobject

提问by chase

I was wondering if anyone had any good ways of quickly explaining how to efficiently and pythonically create user defined objects with optional arguments. For instance, I want to create this object:

我想知道是否有人有任何好的方法来快速解释如何有效地和 Python 地创建带有可选参数的用户定义对象。例如,我想创建这个对象:

class Object:
    def __init__(self, some_other_object, i, *j, *k):
        self.some_other_object = some_other_object
        self.i = i
        # If j is specified, assume it is = i
        if(j==None):
            self.j = i
        else:
            self.j = j
        # If k is given, assume 0
        if(k==None):
            self.k = 0
        else:
            self.k = k

Is there a better way to do this?

有一个更好的方法吗?

EDIT:I changed the code so that it is more broad and more easily understood.

编辑:我更改了代码,使其更广泛且更易于理解。

采纳答案by toxotes

You can set default parameters:

您可以设置默认参数:

class OpticalTransition(object):
    def __init__(self, chemical, i, j=None, k=0):
        self.chemical = chemical
        self.i = i
        self.k = k
        self.j = j if j is not None else i

If you don't explicitly call the class with jand k, your instance will use the defaults you defined in the init parameters. So when you create an instance of this object, you can use all four parameters as normal: OpticalTransition('sodium', 5, 100, 27)

如果您没有使用jand显式调用类k,您的实例将使用您在 init 参数中定义的默认值。因此,当您创建此对象的实例时,您可以照常使用所有四个参数:OpticalTransition('sodium', 5, 100, 27)

Or you can omit the parameters with defaults with OpticalTransition('sodium', 5), which would be interpreted as OpticalTransition('sodium', 5, None, 0)

或者你可以省略带有默认值的参数 OpticalTransition('sodium', 5),这将被解释为OpticalTransition('sodium', 5, None, 0)

You can use some default values but not all of them as well, by referencing the name of the parameter: OpticalTransition('sodium', 5, k=27)uses j's default but not k's.

通过引用参数的名称,您可以使用一些默认值,但也不能使用全部默认值:OpticalTransition('sodium', 5, k=27)使用j的是默认值而不是使用默认值k

Python won't allow you to do j=ias a default parameter (iisn't an existing object that the class definition can see), so the self.jline handles this with an ifstatement that in effect does the same thing.

Python 不允许您将其j=i作为默认参数(i不是类定义可以看到的现有对象),因此该self.j行使用if实际上执行相同操作的语句来处理此问题。

回答by ronak

You could pass in the args as a dict object and parse through the dict to get whatever you want. If it is not passed, get function will return None and you could check the existence like that.

您可以将 args 作为 dict 对象传入并解析 dict 以获得您想要的任何内容。如果没有通过, get 函数将返回 None ,您可以像这样检查是否存在。

class Optioncal_transition(object):
  def __init(self, **args):
    self.chemical = args.get('chemical')
    self.i = args.get('i')
    self.j = args.get('j', self.i)

By default, the getfunction will return None. So if the value exists for j, that will be assigned to self.j otherwise it will be assigned the same value as i

默认情况下,该get函数将返回None. 因此,如果值存在于j,则将分配给 self.j 否则将分配与相同的值i

回答by mertzkeaton

I am too new to stackoverflow to up-vote or comment, but I approve of ronak's answer. Gareth Latty's comment about default parameters is addressed by using the [default] option of the get method.

我太新了,无法在 stackoverflow 上投票或发表评论,但我同意 ronak 的回答。Gareth Latty 关于默认参数的评论是通过使用 get 方法的 [default] 选项解决的。

dictionary.get(key[, default])

using **args allows for less/ more readable code when there are many optional variables to be passed. It is simply passing passing dictionary key-value pairs as parameters.

当有许多可选变量要传递时,使用 **args 允许更少/更易读的代码。它只是将字典键值对作为参数传递。