[Tutor] class data member and objects of class in python

Alan Gauld alan.gauld at btinternet.com
Thu Sep 12 15:39:53 CEST 2013


On 12/09/13 10:10, zubair alam wrote:
> class PizzaShop():
>      pizza_stock = 10
>      def get_pizza(self):
>          while PizzaShop.pizza_stock:
>              PizzaShop.pizza_stock -= 1
>              yield "take yours pizza order, total pizzas left
> {}".format(PizzaShop.pizza_stock)
>
> mypizza_shop = PizzaShop()
> pizza_order = mypizza_shop.get_pizza()
>
> for order in pizza_order:
> print "{}".format(repr(order))

You might as well just use

print order

> domino_pizza_store = mypizza_shop.get_pizza()
> print "{}".format(repr(domino_pizza_store.next()))
>
> mypizza_shop.pizza_stock = 10

This preobably isn't doing what you think it is.
This is creating a new instance attribute in the
mypizza_shop instance it is not resetting the
class attribute. For that you would need to use

PizzaShop.pizza_stock = 10

> can't we again use the same object mypizza_shop
 > once its generator is exhausted

You can't use the same iterator again but you can
get a new one. But your problem here is that you have
not reset the class stock level.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list