对象创建

时间:2013-03-21 14:35:39

标签: list object input python-3.x

这仅仅是为了“学习的乐趣”。我完全是从书本和教程中自学成才,而且对编程也很新。我正在尝试探索从列表中创建对象的概念。这就是我所拥有的:

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”的对象的新实例?如果是这样,我如何检查物体的存在?如果我将对象存储在变量中,那么来自我的顶部代码片段的循环不会在每次迭代时覆盖变量吗?并且我的“print”语句是否正在运行,因为该对象存在,或者因为它的下一行代码?很抱歉我的问题很长,但如果我提供更好的信息,我相信我能得到更好的答案。

1 个答案:

答案 0 :(得分: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