Question about instantiating class objects in a method

Hi all,

Not having an issue completing the project but just curious about how something works. I’ve tried thinking it through but my brain is just exploding. Link to the project is here.

def sell_artwork(self, artwork, price):

   if artwork.owner == self:

     new_listing = Listing(artwork, price, self)


What this function is meant to do is make a new instance of Listings with the given parameters, then put it into the Marketplace immediately. All fine. It works. My question is how come when I run it more than once, the previous ‘new_listing’ doesn’t get overriden? I ran it and sure, it works just fine (which I thought it would break!). But why? Surely it would have made new_listing the new one, since there is only one object called new_listing in Listings, even after it’s added to the Marketplace.

Hope I’m explaining my question clearly:

  • How come when I run this code, I create a new Listing without over-writing the previous one, given I have no way of assigning it a different name?

Hello @argentheinkel8722901, and welcome to the Codecademy Forums!

By the time you execute the sell_artwork method again, the previously created instance of Listing has already been added to the listings. You no longer need to have that information stored in the new_listing variable, since it has been stored elsewhere. In fact, since that variable is local to the sell_artwork method, it no longer exists after the method terminates. It only exists while the method is executing.

1 Like

Thanks! Speedy too. Yeah, I realised after chatting to someone that it’s more or less a matter of scope, and that what gets placed in arrays is the contents of the object rather than the object itself! It helped be realise that instances of self-created classes behave just the same as any other local variable. Ta!