1

i'm a python newbie! I'm playing with class, lists and dictionary and i have a problem!

i have this piece of code:

class Vacca( object ):
    Munte = dict()

    def __init__( self, nr ):
        self.nome = "VACCA_" + str( nr )
        self.numero = str(nr)
        self.mungiture = []

    def mungi( self, latte ):
        nr = self.numero
        Vacca.Munte[ nr ] = self
        Vacca.Munte[ nr ].mungiture.append( latte )

vacca = Vacca( 1 )
vacca.mungi( "white milk" )

vacca = Vacca( 1 )
vacca.mungi( "black milk" )

vacca = Vacca( 1 )
vacca.mungi( "yellow milk" )

vacca = Vacca( 2 )
vacca.mungi( "dark chocolate" )

for v in Vacca.Munte:
    print Vacca.Munte[v].mungiture

If i run this is the result:

['yellow milk']
['dark chocolate']

but i need this:

['white milk','black milk','yellow milk']
['dark chocolate']

what i'm wrong?

1 Answer 1

4

The problem is that you overwrite the object each time you do vacca = Vacca(1) and erase everything you've done before!

Do like this instead:

vacca = Vacca( 1 )
vacca.mungi( "white milk" )
vacca.mungi( "black milk" )
vacca.mungi( "yellow milk" )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.