繁体   English   中英

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

[英]How to apply '*args' and '*kwargs' to define a `class`

为了进一步扩展,我定义了一个带有args和'kwargs'的Book类。

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'。

如何用一种优雅的方法修复它?

如果您的目标是接受可选的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'

我在这里建议不要使用*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

我建议不要只使用args和kwargs。 但是以防万一您绝对需要它,这是一种方法:

class Book:
    def __init__(self, *args, **kwargs):
       attributes = ['name', 'author']
       for item in zip(attributes, args):
           kwargs[item[0]] = item[1]
       self.name = kwargs.get('name')
       self.author = kwargs.get('author')

    def show(self):
        print('Name={name}, author={author}'.format(name=self.name, author=self.author))

book1 = Book('Python', 'Guido')
book1.show()
book2 = Book(name='Python', author='Guido')
book2.show()
book3 = Book('Python', author='Guido')

执行输出:

Name=Python, author=Guido
Name=Python, author=Guido
Name=Python, author=Guido

暂无
暂无

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

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