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

Dave Angel davea at davea.name
Thu Sep 12 22:15:11 CEST 2013


On 12/9/2013 05:10, zubair alam wrote:


> <div dir="ltr"><div>class PizzaShop():</div><div>    pizza_stock = 10</div><div>    def get_pizza(self):</div><div>        while PizzaShop.pizza_stock:</div><div>            PizzaShop.pizza_stock -= 1</div><div>            yield "take yours pizza order, total pizzas left {}".format(PizzaShop.pizza_stock)</div>
> <div><br></div><div>mypizza_shop = PizzaShop()</div><div>pizza_order = mypizza_shop.get_pizza() </div><div># print "{}".format(repr(pizza_order.next()))</div><div><br></div><div>for order in pizza_order:</div><div>
> <span class="" style="white-space:pre">	</span>print "{}".format(repr(order))</div><div><br></div><div>domino_pizza_store = mypizza_shop.get_pizza()</div><div>print "{}".format(repr(domino_pizza_store.next()))</div>
> <div><br></div><div>mypizza_shop.pizza_stock = 10</div><div><br></div><div>domino_pizza_store = mypizza_shop.get_pizza()</div><div>print "{}".format(repr(domino_pizza_store.next()))</div><div><br></div><div><br>
> </div><div>can't we again use the same object mypizza_shop once its generator is exhausted</div></div><div class="gmail_extra"><br><br><div class="gmail_quote">On Thu, Sep 12, 2013 at 6:53 AM, Marc Tompkins <span dir="ltr"><<a href="mailto:marc.tompkins at gmail.com" target="_blank">marc.tompkins at gmail.com</a>></span> wrote:<br>

Please use text email, not hmtl.  The indentation of your program was
messed up in places, and I can't tell whether it was you or the email
program that messed it up.  This is a text newgroup, and html doesn't
work reliably.

As Alan has said, you're confusing class attributes with instance
attributes.  But I wonder if the mistake is actually the reverse of what
he says.

Do you intend that an instance of PizzaShop refers to a particul pizza
shop, and that it has its own inventory, independent of all other pizza
shop instances?  in that case all use of the class attribute    
pizza_stock = 10 is bogus.

To re-iterate the other point Alan made, an iterator is *required* to
continue to throw Stopiteration once its exhausted and has thrown it
once, even if new items show up that it could have used.

But you can readily make a new iterator from the same mypizza_shop, once
you set its pizza_stock to a nonzero value.

-- 
DaveA




More information about the Tutor mailing list