简体   繁体   中英

How to create class attribute that is an alteration of the same class attribute

I have the following class:

@dataclass
class thing:
    DATE: datetime.datetime
    BEG_DATE: datetime.datetime = self.DATE.replace(day=1)) 

But I get this error:

NameError("name 'DATE' is not defined")

Visual Studio points to line 4 where I'm trying to define BEG_DATE.

1) Why?

2) How can I create the attribute BEG_DATE that takes the DATE attribute and just changes the day to 1?

I've tried field(default_factory=self.DATE.replace(day=1)) , but I got the same error.

For fields that depend on the values of other fields, you need to take advantage of Post-init processing . The way you're doing it now, Python is trying to evaluate self.DATE.replace(day=1) when the class is created, rather than when the instance is created.

from dataclasses import dataclass, field

@dataclass
class thing:
    DATE: datetime.datetime
    BEG_DATE: datetime.datetime = field(init=False)

    def __post_init__(self):
        self.BEG_DATE = self.DATE.replace(day=1)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM