-1

This is a small code in which I have a planets class, and I want to know which was the last planet created.

class Planeta:
    ult=''

    def __init__(self, nombre):
        self.nombre = nombre
        self.ult = nombre #the last
        print(self.nombre, 'construido')

    def last(self):
        print('Ultimo constriuido:',self.ult) #print the last

So I create the planets

urano = Planeta('Urano')
neptuno = Planeta('Neptuno')
pluton = Planeta('pluton')

Then I want to know which was the last one created, so I call the method

urano.last()

But the output of the code is

Ultimo constriuido: Urano

When actually the last planet built is Pluto, I want the output to be

Ultimo constriuido: Pluton

I think I understand why this happens, I understand that if I command to call the last() method, the output is because at that moment that was the last.

But then how do I make the output as I want?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Márquez
  • 91
  • 7
  • 1
    You could store the last planet in the class itself, e.g. `Planeta.ult = nombre`. – sj95126 Aug 07 '22 at 22:40
  • 1
    `last()` is an _instance method_, it only has information about it`self`, so in this case `urano.last` only has information about `urano`. What you need is a class variable (and maybe a classmethod) to track class instances. – Gino Mempin Aug 07 '22 at 22:41

1 Answers1

2

In your __init__ method, you have not modified the ult you originally created. You have created an ult field on the instance self. Rather you need to manage ult as a field for the class itself.

Consider the below trivial example.

>>> class Foo(object):
...   def __init__(self, a):
...     self.a = a
...     Foo.last = a
...
>>> a = Foo("hello")
>>> a.a
'hello'
>>> b = Foo("world")
>>> b.a
'world'
>>> Foo.last
'world'
>>>

Or alternatively:

>>> class Foo(object):
...   def __init__(self, a):
...     self.a = a
...     self.__class__.last = a
...
>>> a = Foo("hello")
>>> b = Foo("world")
>>> Foo.last
'world'
>>>
Chris
  • 26,361
  • 5
  • 21
  • 42