簡體   English   中英

在python中創建新對象不會返回新對象

[英]Creating new object in python is not returning a new object

我是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"]

我不明白為什么這兩個調試數組都不為null,有人可以賜教嗎?

編輯:我發現我在帖子中放入python代碼的錯誤。 我在函數中使用.append(“ a”)

您已將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]

您的代碼中缺少一些內容,例如最重要的是類初始化程序。 正確的代碼如下:

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類教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM