How can I print the name in the class?

class CandleShop:
name = “Here’s a Hot Tip: Buy Drip Candles”
print(name) # This prints before we use the class?
def init(self, stock):
self.stock = stock

I was trying some things in the Candle lesson. I Placed a print statement to print the name variable in the CandleShop class and it executed before the class was called. Why is that?

The interpreter has nothing to bind the print statement to, so executes it immediately upon parsing the class. If we do not want it to execute, then we need to enclose it in a method.

>>> class CandleShop:
	tip = "Here's a Hot Tip: Buy Drip Candles"
	def __init__(self, stock):
		self.stock = stock
	def __str__(self):
		return (self.tip)

>>> shop = CandleShop(200)
>>> shop.stock
>>> print (shop)
Here's a Hot Tip: Buy Drip Candles

Okay, so when this line runs (i am not sure of the correct term)
candle_shop = CandleShop({‘blue’: 6, ‘red’: 2, ‘green’: 0})

So it seems that all the variables and things are run when the above line is executed and assigned even before the method in that class is actually called. I think I see why that is.



1 Like

i just used print(