Skip to content
Advertisement

Two different Python classes sharing attribute with same underlying object

Is it possible in Python to have two objects, each of them an instance of a different class, that always share the same value for a particular attribute?

For instance, suppose the following code:

JavaScript

Here my goal would be for a.grid and b.grid to contain the same value always, regardless of whether one is initialized from the other or which one is modified; the desired output would be then:

JavaScript

In this question it is suggested to use a base class containing a class attribute, and use a static method to modify the desired shared attribute. I would rather not use this solution as I don’t want to have this attribute shared among all instances always, only when it is strictly desired. From this other question, I guess I could use the Mutable Default Argument property to have a shared value for a given parameter, but again, I don’t always want the parameter to be shared.

In short, is it possible to have two objects, each an instance of two different classes, to have a shared parameter?

Advertisement

Answer

You can have a parent class to hold the data:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement