9

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.

1 Answer 1

21

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
Sign up to request clarification or add additional context in comments.

8 Comments

What I can't understand with the mechanism is that in the end, temp remains as a field for the final object... The dataclass mechanism should remove it completely from the fields (as is done when called the module-level fields method, but not done in __dataclass_fields__).
I'm not sure I understand what you're saying. x.temp should lead to an AttributeError
Indeed, I was confused, it leads to an AttributeError as expected.
OK, now I see what was the issue: imagine the same example but now give a default value to temp in the class definition. Now you don't have an AttributeError, which is weird.
ok but this breaks keyword init
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.