1

The need to add a serial number unique across all instances of all derived classes must come up frequently. But I can't find a sample. Or a match to my search of stackoverflow.

If I instantiate a bird, mammal and worm from three classes all derived from Animal, the SN values should be 1,2,3. And then an instance of canine (derived from mammal) should get SN 4. And then next bird gets SN 5.

I've tried several ways and they all fail, so rather than troubleshooting, can someone point me to a good design pattern?

Thanks.

Playing with GAS
  • 565
  • 3
  • 10
  • 18

1 Answers1

3

You can control obj creation by customizing __new__, e.g. to keep track of all instances created and set a "serial" attribute on the newly created object:

class A:
    num_objects = 0
    def __new__(cls):
        obj = super(A, cls).__new__(cls)
        A.num_objects += 1
        obj.serial = A.num_objects
        return obj

    def __str__(self):
        return '<{} with serial number {}>'.format(
            self.__class__.__name__,
            self.serial)

class B(A):
    pass

class C(A):
    pass

a = A()
b = B()
c = C()

print(a)
print(b)
print(c)

# <A with serial number 1>
# <B with serial number 2>
# <C with serial number 3>

From the docs:

Typical implementations create a new instance of the class by invoking the superclass’s new() method using super().new(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

miku
  • 181,842
  • 47
  • 306
  • 310