這僅僅是「學習的樂趣」。我完全從書本和教程中自學,而且對編程還很陌生。我試圖探索一個從列表創建對象的概念。以下是我有:對象創建
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」語句時,它是否創建了一個名爲「dog」的對象的新實例?如果是這樣,我該如何檢查物體的存在?如果我將對象存儲在一個變量中,那麼每次迭代時我的頂級片段中的循環是否會覆蓋該變量?我的「打印」語句是因爲對象存在還是因爲它的下一行代碼而運行?對不起,我的問題的長度,但我相信如果我提供更好的信息,我可以得到更好的答案。
這是有幫助的。所以即使我創建了一個新的Obj('dog'),新的與已經創建的不同,我的循環將繼續添加Obj('dog')的更多實例,只要我輸入它?我認爲這是因爲每個實例都存儲在內存中的不同位置,即<__ main __。0x02F54B50>的Obj對象? – Gregory6106 2013-03-21 15:08:30
對於第二部分,字典應該與對象和列表一起使用?閱讀你的解釋之後有意義。但是,我必須問這個自我挫敗的問題,爲什麼在這種情況下使用對象呢? – Gregory6106 2013-03-21 15:10:01
我不會在這種情況下。對象應該封裝多個相關的信息和與之相關的功能。對象是一個如此大的話題,很難解釋何時在這裏使用它們。 – 2013-03-21 18:01:27