如何应用'* args'和'* kwargs'来定义`class`

时间:2017-11-09 06:45:43

标签: python

为了便于进一步扩展,我使用Book和'kwargs'定义了一个班级args

class Book:
    def __init__(self, *args, **kwargs):
        if args:
            self.name,\
            self.author,\
            = args
        elif kwargs:
            self.__dict__.update(kwargs)

它分别适用于位置和关键字参数

In [62]: book1 = Book('Python', 'Guido')
In [63]: book1.author
Out[63]: 'Guido'

In [65]: book2 = Book(name='Python', author='Guido')
In [66]: book2.name
Out[66]: 'Python'

使用位置和关键字参数的混合进行测试时,错误报告。

In [67]: book3 = Book('Python', author='Guido')
ValueError: not enough values to unpack (expected 2, got 1)

可以使用多个条件或标准定义class修复错误,而无需使用*args或“kwargs”。

如何以优雅的方法修复它?

3 个答案:

答案 0 :(得分:3)

如果您的目标是接受可选的nameauthor参数,则应使用默认参数:

class Book(object):

    def __init__(self, name=None, author=None):
        self.name = name
        self.author = author

这不仅使类定义更简单,而且还在__init__签名中传达了更好的意图:

>>> c = Book("best book", "me")
>>> c.name
'best book'
>>> c.author
'me'
>>> c = Book(author="me", name="best book")
>>> c.name
'best book'
>>> c.author
'me'
>>> c = Book("best_book", author="me")
>>> c.name
'best book'
>>> c.author
'me'

答案 1 :(得分:2)

我会在此提出反对*args**kwargs的建议,因为您希望使用它们的方式不是他们打算使用的方式。只需使用命名参数,您就可以完成所有想要的操作。

class Book:
    def __init__(self, name, author):
        self.name = name
        self.author = author

按预期工作。

In [2]: book1 = Book('Python', 'Guido')

In [3]: book2 = Book(name='Python', author='Guido')

In [4]: book3 = Book('Python', author='Guido')

In [7]: book1.name == book2.name
Out[7]: True

In [8]: book1.name == book3.name
Out[8]: True

In [9]: book2.name == book3.name
Out[9]: True

答案 2 :(得分:0)

我建议反对args和kwargs。但是,万一你绝对需要它,这是一种方式:

def conditions(x):
    if x > 400:
        return "High"
    elif x > 200:
        return "Medium"
    else:
        return "Low"

func = np.vectorize(conditions)
energy_class = func(df_energy["consumption_energy"])

执行输出:

df_energy["energy_class"] = energy_class
相关问题