-1

这只是为了“学习的乐趣”。我完全是从书籍和教程中自学的,而且对编程还是很陌生。我正在尝试探索从列表中创建对象的概念。这是我所拥有的:

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!

我已经做了一些研究并阅读了几条关于创建 dict 来做我想做的事情的评论。我已经构建了一个使用 dict 执行此操作的程序,但出于学习目的,我试图了解这是否可以通过创建对象来完成。似乎一切正常,除了当程序通过遍历列表来检查对象的存在时,它会失败。

然后我这样做了:

>>> 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”的对象的新实例?如果是这样,我如何检查对象的存在?如果我将对象存储在变量中,我的顶部片段中的循环不会在每次迭代时覆盖变量吗?我的“打印”语句是因为对象存在还是因为它的下一行代码而运行?抱歉我的问题太长了,但如果我提供更好的信息,我相信我可以得到更好的答案。

4

1 回答 1

0

对象只是数据和函数的容器。尽管Obj("dog")Obj("dog")是等价的,但它们并不相同。换句话说,每次你打电话给__init__你一个全新的副本。所有不是 的对象None0False评估为的对象,True因此您的if语句成功。

您仍然必须使用字典来查看您过去是否创建过狗。例如,

objects = { "dog" : Obj("dog"), "cat" : Obj("cat") }
if "cat" in objects:
    print objects["cat"].x  # prints cat
于 2013-03-21T15:00:19.793 回答