0

Sorry, if the title seemed a little imprecise.

I'm wondering if there is way of making sure that every instance of an object can have a unique serial number?

class Airplane:
    def __init__(self, name, passenger_hold):
        self.name = name
        self.passenger_hold = passenger_hold

airplane1 = Airplane("Airbus A320", 100)
airplane2 = Airplane("Boeing 747", 250)

How can I make sure that the first airplane has the serial number 0, the second one 1 and so on?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Fabio
  • 23
  • 6

1 Answers1

1

Use a global counter, internal to your class that would give you a new value each time the constructor is called.

class Airplane:
    counter = 0

    def __init__(self, name, passenger_hold):
        self.name = name
        self.passenger_hold = passenger_hold
        self.serial = Airplane.counter
        Airplane.counter += 1
Sociopath
  • 13,068
  • 19
  • 47
  • 75
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62