简体   繁体   中英

Unmutable field on python's dataclass

I have this dataclass:

@dataclass
class Couso:
    nome: str
    date: str = field(default=datetime.now(), init = False)
    id_: str = field(default=key())

Being key() a simple function that returns a str on len 32.

And when i create multiple classes of it (without specifing the id_ obviously) they all share the same id_

But why does it work this way? I cant understand.

Also, would this happen again with the attribute date?

key is called before field is called to create the field, so that every instance will have the same default id_ attribute. It's the same as if you had written

x = key()


@dataclass
class Couso:
    ...
    id_ : str = field(default=x)

If you want to call key each time you create a new instance, use default_factory instead.

id_: str = field(default_factory=key)  # key is not called; it's passed as an object.

The same goes for datetime.now :

date: str = field(default_factory=datetime.now, init = False)

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