2

我是 python 新手。

为什么我打电话时没有得到新对象tempMyObject = myObject()

class myObject(object):
  x = []

def getMyObject():
  tempMyObject = myObject()
  print "debug: %s"%str(tempMyObject.x)
  tempMyObject.x.append("a")
  return tempMyObject
#run
a = getMyObject()
b = getMyObject()

我的调试打印出来:

debug: []
debug: ["a"]

我不明白为什么这两个调试数组都不为空,有人可以赐教吗?

编辑:我发现我在帖子中输入 python 代码的错误。我在我的函数中使用 .append("a")

4

2 回答 2

6

您已创建x为类变量而不是实例变量。要将变量与类的特定实例相关联,请执行以下操作:

class myObject(object):
    def __init__(self): # The "constructor"
        self.x = [] # Assign x to this particular instance of myObject

>>> debug: []
>>> debug: []

为了更好地解释正在发生的事情,请看一下这个小模型,它演示了同样的事情,更明确一点(如果也更详细的话)。

class A(object):
    class_var = [] # make a list attached to the A *class*
    def __init__(self):
        self.instance_var = [] # make a list attached to any *instance* of A

print 'class var:', A.class_var # prints []
# print 'instance var:', A.instance_var # This would raise an AttributeError!

print

a = A() # Make an instance of the A class
print 'class var:', a.class_var # prints []
print 'instance var:', a.instance_var # prints []

print

# Now let's modify both variables
a.class_var.append(1)
a.instance_var.append(1)
print 'appended 1 to each list'
print 'class var:', a.class_var # prints [1]
print 'instance var:', a.instance_var # prints [1]

print

# So far so good. Let's make a new object...
b = A()
print 'made new object'
print 'class var:', b.class_var # prints [1], because this is the list bound to the class itself
print 'instance var:', b.instance_var # prints [], because this is the new list bound to the new object, b

print

b.class_var.append(1)
b.instance_var.append(1)
print 'class var:', b.class_var # prints [1, 1]
print 'instance var:', b.instance_var # prints [1]
于 2013-07-11T20:15:25.787 回答
1

您的代码中缺少一些位,例如首先是类初始化程序。正确的代码如下:

class myObject(object):
    def __init__(self):
         self.x=[] #Set x as an attribute of this object.

def getMyObject():
  tempMyObject = myObject()
  print "debug: %s"%str(tempMyObject.x) #Just after object initialisation this is an     empty list.
  tempMyObject.x = ["a"]
  print "debug2: %s"%str(tempMyObject.x) #Now we set a value to it.
  return tempMyObject
#run
a = getMyObject()
b = getMyObject()

现在调试将首先打印出一个空列表,然后,一旦它被设置,“a”。希望这可以帮助。我建议查看基本的 python 类教程

于 2013-07-11T20:22:34.733 回答