1

Is it possible to change the class of an object? In the following example:

class Fisch:
...

class Trout(Fish):

    def some_special_trout_method:
        ...
...

class Salmon(Fish):
...


...
fisch_object = Trout()

Would it be possible to change the trout into a salmon and keep the class variable values? If this is possible how? And if it's possible, is it a good idea?

Gurkenkönig
  • 678
  • 15
  • 36
  • 2
    It's possible, but *don't*. It's almost always a terrible idea, and it'll cause many more problems than it solves. – user2357112 Aug 27 '18 at 20:03
  • Thanks for the quick answer. What would be the best alternative way to write an object that has many different forms with special methods? A "type" variable and then if else? – Gurkenkönig Aug 27 '18 at 20:13
  • @Gurkenkönig: What is the goal? What sane scenario has a trout miraculously become a salmon? You can easily create new `Salmon`, even rebind an existing variable that used to refer to a `Trout` object to refer to a brand new `Salmon` (e.g. `fisch_object = Salmon()` on a later line drops the existing `Trout` and makes a new `Salmon`), but changing the type of the `Trout` object itself makes no sense, and makes me suspect [you have an XY problem](https://meta.stackexchange.com/q/66377/322040). – ShadowRanger Aug 27 '18 at 20:14
  • I tried to find a simple example (sorry for the stupid fish example). In reality it is about different types of agents in a simulation with different abilities, but the type can change. – Gurkenkönig Aug 27 '18 at 20:17
  • It's also unclear what you mean by "keep the class variable values". Do you want it to *be* a `Salmon`, but still be able to *call* `some_special_trout_method` on it, despite the fact that it is no longer a `Trout`? If so, what about it is really "`Salmon`y" if it's still supposed behave like a `Trout`? – ShadowRanger Aug 27 '18 at 20:17
  • If fisch_object.length = 150 then this property should survive the magic transformation – Gurkenkönig Aug 27 '18 at 20:19
  • @Gurkenkönig: If it's just instance attributes (that is, stuff assigned to with `self.x = y` in `__init__` and the like) that need to survive *and* `Trout` (or whatever is converting it) establishes all the same preconditions expected of a `Salmon`, *and* you don't expect `Trout`-specific methods and class attributes (names assigned to outside any method in the `class` definition) to continue working then this is possible (the duplicates cover how). It's almost always a bad idea though. – ShadowRanger Aug 27 '18 at 20:23

0 Answers0