2015-05-20 14 views
5

Ben oyuncaklar (sayılar) muhafaza edilebileceği bir göğüs temsil aşağıdaki sınıfını yarattı:Python'da bir döngüde, aynı değişkene yeni bir sınıf örneği atar, ancak eski örneğe işaret ediyor mu?

class Chest: 

    toys = [] 

    def __init__(self): 
    return 

    def add(self, num): 
    self.toys.append(num) 
    return 

şöyle bu sınıftır kullandığı ana kod:

room_of_chests = [] 

for i in range(3): 

    print "Chest", i 
    temp = Chest() 

    print "Number of toys in the chest:", len(temp.toys) 

    for j in range(5): 
    temp.add(j) 

    print "Number of toys in the chest:", len(temp.toys) 
    print "" 

    room_of_chests.append(temp) 

Yani, her yineleme için Ben, Chest yeni oluşturmak ve temp noktasını işaret (doğru?). Yani, teoride, her yinelemede, temp boş bir sandıkla başlayıp 5 oyuncaklı bir göğüsle (doğru?) Başlayacaktır.

nedenle, bekliyorum çıktısı: Ancak

Chest 0 
Number of toys in the chest: 0 
Number of toys in the chest: 5 

Chest 1 
Number of toys in the chest: 0 
Number of toys in the chest: 5 

Chest 2 
Number of toys in the chest: 0 
Number of toys in the chest: 5 

, benim asıl alıyorum: Ben yanlış yapıyorum

Chest 0 
Number of toys in the chest: 0 
Number of toys in the chest: 5 

Chest 1 
Number of toys in the chest: 5 
Number of toys in the chest: 10 

Chest 2 
Number of toys in the chest: 10 
Number of toys in the chest: 15 

? Birisi bu durumda örneklemenin nasıl çalıştığını hızlı bir şekilde açıklayabilir mi? Ve Python'daki nesnelere işaret eden değişkenlerin kuralları? Şimdiden teşekkürler.

cevap

10

Sorun, bir sınıf değişkenine sahip olduğunuz ve sınıf değişkenine sahip olmadığınızdır. self'un bir üyesi olarak __init__ işlevinde oluşturarak bir örnek değişkeni yapmak için sınıfınızı değiştirin.

Ayrıca __init__ içinde return kullanmaya gerek yoktur.

class Chest: 

    def __init__(self): 
    self.toys = [] 


    def add(self, num): 
    self.toys.append(num) 

Java veya C++ gibi bir dilden geliyorsanız, bu yaygın bir hatadır.

+1

Python sınıfı öznitelikleri, Java veya C++ statik üye değişkenleri ile tamamen aynı değildir. Python dokümanları, doğru olmayan herhangi bir şeyi ima etmekten kaçınmak için "statik değişken" veya "statik özellik" terimini kullanmaktan kaçınmaya çok dikkat eder ve aynı şeyi burada yapmak daha iyi olur. (Aksi takdirde, harika bir açıklama.) – abarnert

+0

@abarnert, Yorum için teşekkürler. Terminolojiyi güncelleyeceğim. – merlin2011

+0

Oh, ayrıca, '__init__' başlatıcısıdır; Kurucu (nadiren endişelenmeniz gereken) '__new__'. – abarnert

İlgili konular