Issue
I want to populate an attribute of a dataclass using the default_factory
method. However, since the factory method is only meaningful in the context of this specific class, I want to keep it inside the class (e.g. as a static or class method). For example:
from dataclasses import dataclass, field
from typing import List
@dataclass
class Deck:
cards: List[str] = field(default_factory=self.create_cards)
@staticmethod
def create_cards():
return ['King', 'Queen']
However, I get this error (as expected) on line 6:
NameError: name 'self' is not defined
How can I overcome this issue? I don't want to move the create_cards()
method out of the class.
Solution
One possible solution is to move it to __post_init__(self)
. For example:
@dataclass
class Deck:
cards: List[str] = field(default_factory=list)
def __post_init__(self):
if not self.cards:
self.cards = self.create_cards()
def create_cards(self):
return ['King', 'Queen']
Output:
d1 = Deck()
print(d1) # prints Deck(cards=['King', 'Queen'])
d2 = Deck(["Captain"])
print(d2) # prints Deck(cards=['Captain'])
Answered By - momo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.