Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.7: Initialize objects with dataclasses module?

Here is the my code in python 3.6

class A(object)

    def __init__(self, a: str):
        self._int_a: int = int(a)  # desired composition

    def get_int_a(self) -> int:
        return self._int_a   

I want to rewrite this code in python 3.7, how can i initialize self._int_a: int = int(a) with dataclasses module?

I know that i can do something like that but i can't get how to initialize _a: int = int(a) or similar to that.

from dataclasses import dataclass


@dataclass
class A(object):
    _a: int = int(a)  # i want to get initialized `int` object here

def get_int_a(self) -> int:
    return self._a

Thanks in advance for your ideas and suggestions.

like image 215
Vladimir Yahello Avatar asked May 10 '26 10:05

Vladimir Yahello


1 Answers

Do away with getters and setters entirely and just use attribute access. We can define an init only field that accepts a string and then convert that string to an integer field in our __post_init__ call.

from dataclasses import dataclass, InitVar, field

@dataclass
class A:
    temp: InitVar[str]
    a: int = field(init=False)
    def __post_init__(self, temp):
        self.a = int(temp)

x = A("1")
print(type(x.a), x.a)
# <class 'int'> 1
like image 133
Patrick Haugh Avatar answered May 12 '26 23:05

Patrick Haugh



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!