これは単に「学ぶ喜び」のためです。私は本やチュートリアルから完全に独学でプログラミングを始めたばかりです。リストからオブジェクトを作成するという概念を探求しようとしています。ここに私が持っているものがあります:
class Obj: # Creates my objects
def __init__(self, x):
self.name = x
print('You have created a new object:', self.name)
objList = []
choice = 'y'
while choice != 'n': # Loop that runs until user chooses, 'n' to quit
for i in objList:
print(i) # Iterates through the list showing all of the objects added
for i in objList:
if Obj(i):
print(i, 'has already been created.') # Checks for existance of object, if so skips creation
else:
createObj = Obj(i) # Creates object if it doesn't exist
choice = input('Add object? (y / n): ')
if choice == 'y':
newObject = input('Name of object to add: ')
if newObject in objList: # Checks for existance of user enrty in list
print(newObject, 'already exists.') # Skips .append if item already in list
else:
objList.append(newObject) # Adds entry if not already in list
print('Goodbye!')
これを実行すると、次のようになります。
Add object? (y / n): y
Name of object to add: apple
apple
You have created a new object: apple # At this point, everything is correct
apple has already been created. # Why is it giving me both conditions for my "if" statement?
Add object? (y / n): y
Name of object to add: pear
apple
pear
You have created a new object: apple # Was not intending to re-create this object
apple has already been created.
You have created a new object: pear # Only this one should be created at this point
pear has already been created. # Huh???
Add object? (y / n): n
Goodbye!
私はすでにいくつかの調査を行っており、私がやろうとしているように見えることを行うための辞書の作成に関するいくつかのコメントを読んでいます。辞書を使用してこれを行うプログラムを既に作成しましたが、学習目的で、代わりにオブジェクトを作成することでこれを実行できるかどうかを理解しようとしています。プログラムがリストを繰り返し処理してオブジェクトの存在をチェックする場合を除いて、すべてが機能しているように見えますが、失敗します。
次に、これを行いました:
>>> Obj('dog')
You have created a new object: dog
<__main__.Obj object at 0x02F54B50>
>>> if Obj('dog'):
print('exists')
You have created a new object: dog
exists
これは私を理論に導きます。「if」ステートメントを入力すると、「犬」という名前のオブジェクトの新しいインスタンスが作成されますか? もしそうなら、どうすればオブジェクトの存在を確認できますか? オブジェクトを変数に格納すると、一番上のスニペットからのループが反復ごとに変数を上書きしませんか? そして、オブジェクトが存在するため、またはコードの次の行のために、私の「印刷」ステートメントが実行されていますか? 質問が長くなって申し訳ありませんが、より良い情報を提供すれば、より良い回答が得られると確信しています。