Questions like this exist, but none exactly like this, and I found no completely satisfactory answers.
I'm doing an agent-based biological model. Suppose I have a class of cell type A, and one of type B. They age according to a clock. Suppose when a cell of type A reaches a certain age, it changes to a cell of type B.
I have an inventory of cells. I don't want to just create new B cells, and add them to the inventory, and leave the A cells still in the inventory.
This appears to work, but is it safe?
class B(object):
pass
class A(object):
def changeToB(self):
self.__class__ = B
Or, is there a better approach?
In Python, abstract base classes provide a blueprint for concrete classes. They don't contain implementation. Instead, they provide an interface and make sure that derived concrete classes are properly implemented. Abstract base classes cannot be instantiated.
Python provides a __bases__ attribute on each class that can be used to obtain a list of classes the given class inherits. The __bases__ property of the class contains a list of all the base classes that the given class inherits.
If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.
A base class is a class, in an object-oriented programming language, from which other classes are derived. It facilitates the creation of other classes that can reuse the code implicitly inherited from the base class (except constructors and destructors).
While it may be safe for the interpreter, it is definitely unsafe to one trying to understand what's happening.
It is hard to find a more natural mapping to object design than a biological cell and you are trying to discard what is naturally there. A cell has-a age and various mechanisms turn on and off as a function of age. In the world, an osteoblast doesn't pop out of existence and an osteocyte takes its place, but rather the cell retains its "identity" but behaves differently depending on state values like age.
I'd certainly take considerations like that into the object model if I were coding such a model.
I tried that many years ago while working on a parser. It seemed to do what I wanted at the time, so was safe enough from the language perspective, but now I am older and wiser I don't think I'd use it for code that anyone else might have to maintain - I don't think it's very "safe" from that perspective
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With