2013-03-21 156 views
-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! 

我已经做了一些研究和阅读有关创建一个字典做它似乎我一些意见米试图做。我已经建立了一个使用字典来实现这个功能的程序,但是为了学习目的,我试图了解这是否可以通过创建对象来完成。它看起来好像一切正​​常,除了程序通过遍历列表来检查对象的存在时,它就会失败。

我那么做:

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

回答

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 
+0

这是有帮助的。所以即使我创建了一个新的Obj('dog'),新的与已经创建的不同,我的循环将继续添加Obj('dog')的更多实例,只要我输入它?我认为这是因为每个实例都存储在内存中的不同位置,即<__ main __。0x02F54B50>的Obj对象? – Gregory6106 2013-03-21 15:08:30

+0

对于第二部分,字典应该与对象和列表一起使用?阅读你的解释之后有意义。但是,我必须问这个自我挫败的问题,为什么在这种情况下使用对象呢? – Gregory6106 2013-03-21 15:10:01

+0

我不会在这种情况下。对象应该封装多个相关的信息和与之相关的功能。对象是一个如此大的话题,很难解释何时在这里使用它们。 – 2013-03-21 18:01:27