0

I'd like to make a class automatically log all the objects of that class when they are instantiated, so, given this little piece of code:

class Comet:
    comets = []

    __init__(self, mass):
        self.mass = mass
        Comet.comets.append(**instance name as a string**)


HalleysComet = Comet(3*10**14)
Temple 1 = Comet(7.9*10**13)

print(str(Comet.comets))

The output would be this:

['HalleysComet', 'Temple 1']
  • 5
    No. Creating the instance takes place **first**, assignment only when that succeeds. – Martijn Pieters Feb 15 '17 at 17:13
  • 5
    Also, objects do not necessarily end up being assigned to a name. What about `some_list = [Comet(), Comet()]`? – Martijn Pieters Feb 15 '17 at 17:14
  • 3
    Also, objects do not necessarily end up being assigned to a single name. What about `Halleys = Shoemaker = Comet()`. – Robᵩ Feb 15 '17 at 17:16
  • 2
    https://docs.python.org/3/library/enum.html#planet – Josh Lee Feb 15 '17 at 17:19
  • 1
    You could make your class associate names with instances by making the `coments` class attribute a dictionary and adding a `name` argument to the `__init__()` method. In the method you can add the value of `self` to the dictionary using `name` as its key. This isn't exactly what you asked, but may be good enough for whatever you're trying to accomplish. – martineau Feb 15 '17 at 18:14

0 Answers0