2017-05-18 15 views
-1

python类的实例行为不一致。python - 类实例的不一致行为

Code.1

class A(): 
     def __init__(self, x): 
      self.x = x 
     def update(self, x): 
      self.x = x 

    a = A(3) 
    a.update(5) 
    print a.x # prints 5 

Code.2

class A(): 
     def __init__(self, x): 
      self.x = x 
     def update(self, x): 
      self = A(x) 

    a = A(3) 
    a.update(5) 
    print a.x # prints 3 

为什么 'x' 的属性得到的第一个片段更新,并在第二届一个是没有得到更新?

+1

无法重现。这(正确地)打印''你确定你正在执行你正在显示的代码吗? – dhke

+0

@dhke:对不起,我在第二个代码段中犯了一个错误,请立即检查。 –

回答

1

分配给self不会更改当前对象。它只是给(本地)自我参数变量分配一个新值。

唯一的特殊待遇,该self得到的是调用过程中,在这个意义上,

a.update(x) 

相当于

A.update(a, x) 

分配到self只覆盖本地参数的值:

def update(self, x): 
    # overwrite the value of self with a different instance of A 
    # This has no effect outside of update(). 
    self = A(x) 

a = A(3) 
a.update(5) 

在这个cas e a仍然是来自A(3)的相同实例。您在update()内创建了一个新的A实例,并将其分配给self参数,但该修改不会在update()之外转移。