是否可以在数据类中使用* args? [英] Is it possible to use *args in a dataclass?
问题描述
我最近开始使用数据类,它们将是对它们的不错补充. 3.7.我很好奇是否可以使用数据类来重新创建此类的相同功能.
I recently started using dataclasses and they will be a nice addition to 3.7. I'm curious if or how it is possible to recreate the same functionality of this class using dataclasses.
class Nav(object):
def __init__(self, name:str, menu, page, *submenus):
self.name = name
self.menu = menu
self.page = page
self.submenus = submenus
foo = Nav("name", "menu", "page")
这不起作用.引发异常TypeError: __init__() missing 1 required positional argument: 'submenus'
This doesn't work. Raises Exception TypeError: __init__() missing 1 required positional argument: 'submenus'
@dataclass
class Nav(object):
name:str
menu: Any
page: Any
submenus: tuple
foo = Nav("name", "menu", "page")
我认为这是因为该类没有进行参数解压缩的指令. 是否可以通过某种方法来指示数据类装饰器需要解压缩子菜单?
I assume this is because the class doesn't have the instructions to do the unpacking of the arguments. Is there some way to instruct the dataclass decorator that submenus needs to be unpacked?
推荐答案
I see in the PEP an example of how to override the __init__
.
有时生成的 init 方法不足够.例如, 假设您想要一个对象来存储* args和** kwargs:
Sometimes the generated init method does not suffice. For example, suppose you wanted to have an object to store *args and **kwargs:
@dataclass(init=False)
class ArgHolder:
args: List[Any]
kwargs: Mapping[Any, Any]
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
a = ArgHolder(1, 2, three=3)
这篇关于是否可以在数据类中使用* args?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!