2

I have a dataclass that I would like to set a value when initializing the class.

@dataclass
class classA:

    __data: DataFrame
    __Limit: float
    __totalLimit: float = field(init=False)


    def __post_init__(self):

        # This Does not work
        __setTotalLimit()

        # This works when i put the logic in.
        # self.__totalLimit = self.__data['Amount'].sum()

    def __setTotalLimit(self):
        self.__totalLimit = self.__data['Amount'].sum()

This is the error I am getting: NameError: name '_classA__setTotalLimit' is not defined

Basically as soon as data is passed in, i need to sum up a column and set that as a variable because it will be used throughout the script.

user3783961
  • 59
  • 1
  • 8

2 Answers2

3

Use like this:

def __post_init__(self):
    self.__setTotalLimit()

If the field does not actually need data from the instance, then don't use __post_init__ at all, but use the default_factory option when adding the field itself, providing a zero-arg callable.

Note that it is strange to __name_mangle every dataclass field like that. You should probably just use normal attributes.

X Æ A-Xiii
  • 576
  • 4
  • 14
3

You forgot to refer to the method using self:

def __post_init__(self):
    self.__setTotalLimit()
Jay Mody
  • 3,727
  • 1
  • 11
  • 27