【问题标题】:Object creation对象创建
【发布时间】:2013-03-21 14:35:38
【问题描述】:

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

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

【问题讨论】:

    标签: list object input python-3.x


    【解决方案1】:

    对象只是数据和函数的容器。尽管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
    

    【讨论】:

    • 这很有帮助。所以即使我创建了一个新的 Obj('dog'),新的 Obj('dog') 与已经创建的不同,我的循环将继续添加 Obj('dog') 的更多实例,只要我输入它?我认为这是因为每个实例都存储在内存中的不同位置,即 <__main__.obj object at> ?
    • 而对于第二部分,字典应该与对象和列表一起使用吗?看完你的解释就明白了。但是我必须问这个自欺欺人的问题,为什么要在这种情况下使用对象呢?
    • 我不会在这种情况下。对象应该封装多个相关的信息和与之相关的功能。对象是一个很大的话题,很难在这里解释何时使用它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2013-05-11
    • 2011-02-14
    • 2013-04-10
    • 2013-02-11
    相关资源
    最近更新 更多