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?
dataclasses has a special method called __post_init__ . As the name clearly suggests, this method is called right after the __init__ method is called. Going back to the previous example, we can see how this method can be called to initialize an internal attribute that depends on previously set attributes.
DataClasses are like normal classes in Python, but they have some basic functions like instantiation, comparing, and printing the classes already implemented. Parameters: init: If true __init__() method will be generated. repr: If true __repr__() method will be generated.
Defining a data class. A Python class is a program used to create objects and their properties. We use the keyword class to create a class in Python. For class attributes to be initialized, we use a constructor method called __init__() which is called when an object is created in a Python class.
A data class refers to a class that contains only fields and crude methods for accessing them (getters and setters). These are simply containers for data used by other classes. These classes don't contain any additional functionality and can't independently operate on the data that they own.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With