Reputation: 3
class Pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
def __repr__(self):
return f'Pizza({self.ingredients!r})'
why can this Pizza(['mozzarella', 'tomatoes'])
work? Normally i will do like this Pizza1 = Pizza(['mozzarella', 'tomatoes'])
in this situation:
class Pizza():
pass
what if i input two Pizza()
? are the two Pizza()
a new object? i have tried this in my Vscode, but it returns the same ID address.
Upvotes: 0
Views: 76
Reputation: 1038
Pizza(['mozzarella', 'tomatoes'])
is an expression, just like 1+1
or f(1, 2, 3)
or "dogs"
. At runtime, this expression evaluates to a new instance of Pizza
, different from any other instance in the program. You can therefore write things like:
def printPizza(pizza):
print("Here's a pizza")
print(repr(pizza))
printPizza(Pizza(['mozzarella', 'tomatoes']))
When you have a statement (not an expression!) like pizza = Pizza(['mozzarella', 'tomatoes'])
, what happens at runtime is that the result of evaluating the Pizza(...)
expression (i.e. the new instance of Pizza
) is assigned to the pizza
variable. Of course, then you can easily run printPizza(pizza)
.
If the Pizza()
expression is run twice, each time it returns an instance of Pizza
that's distinct from any other instance currently alive in the program. However, if the instance returned from the earlier Pizza()
call is no longer alive, then the new call to Pizza()
may have the same id as the earlier instance (that's no longer available).
For example, in IDLE:
>>> id(Pizza())
65959272
>>> id(Pizza())
65959272
Because the instance returned from the first call to Pizza()
is no longer stored anywhere when the second call to Pizza()
executes, the id can safely be reused. (There are never two pizzas alive at the same time with the same id.)
But if you do something like this:
def printIds(pizza1, pizza2):
print(id(pizza1))
print(id(pizza2))
printIds(Pizza(), Pizza())
You'll see that two unique IDs are printed. This is because both pizza instances are alive at the time when the ids are printed (one is stored in pizza1
and the other in pizza2
) so each must have a unique ID.
Upvotes: 3