I need a class function which creates a new instance from existing instance attributes.
This seems to me to be a factory function (hence the thought that it could be a classmethod), but it needs the class to be instanced.
Should/May I use the decorator @classmethod
?
from dataclasses import dataclass
@dataclass
class Coin:
obverse: str
reverse: str
def flip(self):
return Coin(self.reverse, self.obverse)
cent = Coin('cent_ob', 'cent_rev')
flipped_cent = cent.flip()
cent
Out[20]: Coin(obverse='cent_ob', reverse='cent_rev')
flipped_cent
Out[21]: Coin(obverse='cent_rev', reverse='cent_ob')
This works.
But if I use the decorator @classmethod
, it does not any longer.
from dataclasses import dataclass
@dataclass
class Coin:
obverse: str
reverse: str
@classmethod
def flip(cls, self):
return cls(self.reverse, self.obverse)
cent = Coin('cent_ob', 'cent_rev')
flipped_cent = cent.flip()
TypeError: Coin.flip() missing 1 required positional argument: 'self'
Please, what case am i dealing with here?
Is there another decorator more suited to this case?
I believe that my primary goal is more to have a decorator explicitely indicating “hey, you have a factory function here”.
Thank you for your help!