我是python新手!
我在玩课堂,列表和字典,但我有问题!

我有这段代码:

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


如果我运行这是结果:

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


但我需要这个:

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


我错了吗?

最佳答案

问题在于,每次执行vacca = Vacca(1)时,您都将覆盖该对象,并擦除之前已完成的所有操作!

改为这样:

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

关于python - Python:如何添加对象的静态类数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29953864/

10-12 15:45