Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe to change base class in python?

Tags:

python

class

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?

like image 738
abalter Avatar asked Jul 11 '12 21:07

abalter


People also ask

What does base class mean in Python?

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.

What is __ base __ in Python?

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.

Can child class override the properties of parent class in Python?

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.

Why do we use base class?

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).


2 Answers

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.

like image 172
msw Avatar answered Oct 16 '22 20:10

msw


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

like image 3
John La Rooy Avatar answered Oct 16 '22 20:10

John La Rooy