Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut for assigning attributes from __init__

Tags:

python

I quite often find myself directly assigning a class' attributes from values passed to the __init__:

class SomeThing:
    def __init__(self, a, b, c, d, e ...):
        self.a = a
        self.b = b
        self.c = c
        ...

Is there some way to streamline this?

like image 720
snazzybouche Avatar asked May 18 '26 01:05

snazzybouche


1 Answers

Dataclasses are designed especially for this kind of __init__ functions.

With them you can write your class like this:

@dataclass
class SomeThing:
    a: int
    b: str
    c: float
    d: bool
    e: list

    # __init__ will be generated automatically based on fields declaration above
like image 91
sanyassh Avatar answered May 20 '26 13:05

sanyassh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!