python 类初始化器中的可选参数 [英] optional arguments in initializer of python class

查看:82
本文介绍了python 类初始化器中的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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?

我更改了代码,使其更广泛且更易于理解.

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

推荐答案

可以设置默认参数:

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

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

If you don't explicitly call the class with j and 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)

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

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, k=27) 使用 j 的默认值,但不是 k 的.

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.

Python 不允许您将 j=i 作为默认参数(i 不是类定义可以看到的现有对象),因此self.j 行使用 if 语句处理这个问题,实际上做了同样的事情.

Python won't allow you to do j=i as a default parameter (i isn't an existing object that the class definition can see), so the self.j line handles this with an if statement that in effect does the same thing.

这篇关于python 类初始化器中的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆