1

Suppose I have the following example:

import uuid

class A:
    def __init__(self):
        self.id = uuid.uuid4().hex

class B(A):
    def __init__(self):
        super().__init__()
        self.print_id()

    def print_id(self):
        print(self.id)

class C(A):
    def __init__(self):
        super().__init__()
        self.print_id()

    def print_id(self):
        print(self.id)

We have class B and C that are inheriting A. Once B or C are instantiated, they will print the unique ID created in the super class. The issue I am running into here is that each time B or C is instantiated, there is a brand new id created for class A. I would like to print/use the SAME ID for both class B and C. In other words, I only want to have one instance of class A to be used for B and C. Without involving any sort of logic surrounding singletons, how can I achieve this? How can class C know that class B has already initialized class A, therefore an ID already exists? I am attempting to create a base class that is initialized only once, and that ID is inherited by all the sub classes. Any help here would be appreciated.

Dan
  • 45,079
  • 17
  • 88
  • 157
  • You cannot inherit from instances, but from classes. The way your class is written, a new id gets created for every instance. – juanpa.arrivillaga Mar 17 '20 at 17:50
  • @juanpa.arrivillaga thanks for this note. I have noticed this. If I would like to derive from a base that only creates this ID once, how can I achieve this? – Karanvir Ghumaan Mar 17 '20 at 17:51
  • You essentially want each class to have a unique id, where every instance of those classes shares the same id? I'm still not exactly sure what you want. – juanpa.arrivillaga Mar 17 '20 at 17:54

1 Answers1

1

You can use a class attribute

e.g.

class A:
    static_id = uuid.uuid4().hex

    def __init__(self):
        pass

The rest of the code will be the same.

I changed the name of the id member, because it shadowed the name of a built-in function.

(This solution smells to me a little, but I do not understand your problem enough to suggest anything better).

chepner
  • 497,756
  • 71
  • 530
  • 681
jon
  • 215
  • 2
  • 12