Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Instance class mutation

Tags:

python

I have two classes:

class Egg:
    def __init__(self):
        self._color = 'White'

class Larvae(Egg):
    def __init__(self):
        super().__init__()
        self._color = 'Transparente'

To illustrate ...

Ant cycle illustration

So, in my code I have an Egg instance. When it's time I would like transform them into Larvae instances. I can create a Larvae instance and hand copy informations about a "previous" Egg instance. What does Python offer for something like that? For "mute" an instance in instance of subclass of its class?

Edit: As commented below, OOP in this question is not good way to do the wanted behavior. So, keep this in mind when reading answer

like image 887
bux Avatar asked Feb 09 '26 19:02

bux


1 Answers

How about using a state-based approach?

class Ant:
    def __init__(self, state='egg'):
        self.state = state

    @property
    def color(self):
        return {
            'egg': 'Transparent',
            'larvae': 'White,'
        }[self.state]

    def hatch(self):
        if self.state == 'egg':
            self.state = 'larvae'
        else:
            raise Exception('Cannot hatch if not an egg!')
like image 186
Nick T Avatar answered Feb 12 '26 10:02

Nick T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!