Is it possible to use *args in a dataclass?

走远了吗. 提交于 2020-01-14 07:05:35

问题


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")

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?


回答1:


I see in the PEP an example of how to override the __init__.

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)


来源:https://stackoverflow.com/questions/50764873/is-it-possible-to-use-args-in-a-dataclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!