私は Python を初めて使用し、Swaroop CH の「A Byte of Python」の例に取り組んできました。私を__del__
困惑させている方法でいくつかの動作が見られます。
基本的に、次のスクリプトを実行すると(Python 2.6.2で)
class Person4:
'''Represents a person'''
population = 0
def __init__(self, name):
'''Initialize the person's data'''
self.name = name
print 'Initializing %s'% self.name
#When the person is created they increase the population
Person4.population += 1
def __del__(self):
'''I am dying'''
print '%s says bye' % self.name
Person4.population -= 1
if Person4.population == 0:
print 'I am the last one'
else:
print 'There are still %d left' % Person4.population
swaroop = Person4('Swaroop')
kaleem = Person4('Kalem')
Python コンソール (または Spyder インタラクティブ コンソール) を使用すると、次のように表示されます。
execfile(u'C:\1_eric\Python\test1.py')
Swaroopの
初期化 Kalem の初期化execfile(u'C:\1_eric\Python\test1.py') Swaroop を
初期化 して い ます
2 回目の実行の__del__
直後にメソッドが呼び出されるのはなぜですか?
同じインスタンス名 (「swaroop」と「kaleem」) が使用されているため、元のインスタンスを解放し、それをガベージ コレクションしていると推測しています。しかし、これは現在の人口数に大混乱を引き起こしているようです。 __init__
ここで何が起こっているのですか?
この種の混乱を避ける良い方法は何ですか? ?
の使用は避けてください。__del__
再利用する前に既存のインスタンス名を確認しますか? ...
ありがとう、エリック