2012-01-08 11 views
0

コマンドプロンプトでこのコードを実行すると、作成するPersonが自動的に削除されますが、IDLEで削除されません。どうして?cmdではクラス削除がIDLEにはありません

注:このここではアドレス帳(辞書のリスト)

を作成することになっているプログラムは、私のコードです: リスト= []

class bookEntry(dict): 
    total = 0 

    def __init__(self): 
     bookEntry.total += 1 
     self.d = {} 

    def __del__(self): 
     bookEntry.total -= 1 
     list.remove(self) 

class Person(bookEntry): 
    def __init__(self, n): 
     bookEntry.__init__(self) 
     self.n = n 
     print '%s has been created' % (self.n) 

    def __del__(self): 
     print '%s has been deleted' % (self.n) 

    def addnewperson(self, n, e = '', ph = '', note = ''): 
     self.d['name'] = n 
     self.d['email'] = e 
     self.d['phone'] = ph 
     self.d['note'] = note 

     list.append(self) 

私はでコードを実行しますstartup機能:コードはIDLEで実行された場合

def startup(): 
    aor = raw_input('Hello! Would you like to add an entry or retrieve one?') 
    if aor == 'add': 
     info = raw_input('Would you like to add a person or a company?') 
     if info == 'person': 
      n = raw_input('Please enter this persons name:') 
      e = raw_input('Please enter this persons email address:') 
      ph = raw_input('Please enter this persons phone number:') 
      note = raw_input('Please add any notes if applicable:') 

      X = Person(n) 
      X.addnewperson(n, e, ph, note) 
startup() 

私は、次のプロンプトが表示され、そして次の答えを提出:

''' 
    Hello! Would you like to add an entry or retrieve one?add 
    Would you like to add a person or a company?person 
    Please enter this persons name:Pig 
    Please enter this persons email address:[email protected] 
    Please enter this persons phone number:333-333-3333 
    Please add any notes if applicable:one of three 
    Pig has been created 
''' 

ここで、Pigは作成され、削除されない。しかし、cmdで.....

''' 
    Hello! Would you like to add an entry or retrieve one?add 
    Would you like to add a person or a company?person 
    Please enter this persons name:Pig 
    Please enter this persons email address:[email protected] 
    Please enter this persons phone number:333-333-3333 
    Please add any notes if applicable:one of three 
    Pig has been created 
    Pig has been deleted 
''' 

なぜピッグは削除されますか? __del__は決して呼ばれません...

答えて

0

プログラムが終了すると、すべての変数が自動的に削除されます(そうでなければ、メモリリークが発生します)。 IDLEは環境を開いたままにしておくので、作成した変数を引き続き使用することができます。

注:私のオリジナルの答えは、私はあなたがIDLEで実行しながら、Pythonのプロセスはまだあなたがこれを実行した後も実行されているラインに

list = [] 

list.append(self) 
+0

@ DavidRobinson - Ahh参照してください。ここでの解決策は何でしょうか? Xをリストに追加しますか? Xを単に追加しないで返すだけなら、後でどのように取り出すことができますか? – dopatraman

+1

申し訳ありませんが、問題は、関数が返された後で削除されたということではなく(プログラム変数をリスト変数に追加した)、プログラムが終了したときに削除していたことです。解決策の必要はありません。コードをもっと書くと、変数はまだ存在します(プログラム全体が終了した後に存在する必要はありません)。 –

1

を逃しmistaken-ましたあなたがIDLEを終了しない限り、しかし、コマンドラインでは、pythonプロセスがプログラムを実行して終了します。だから、__del__が出場します。オブジェクトの参照カウントがゼロの場合、それは自動的に呼び出されて破壊されます。オブジェクトは削除されます。あなたのプログラムが終了し、Pythonのプロセス自体が終了すると、それも存在する必要はありません。

Reference

関連する問題