2014-10-09 63 views
0

说我有这样的代码:在从其他类(Python)的类变化的变量

class hello_world(): 
    def define_hello(self): 
     self.hello = "hello" 
    def say_hello(self): 
     print self.hello 

class change_to_goodbye(): 
    def __init__(self): 
     self.helloWorld = hello_world() 
    def hello_to_goodbye(self): 
     self.helloWorld.hello = "goodbye" 

class other_class(): 
    def __init__(self): 
     self.helloWorld = hello_world() 
     self.changeToGoodbye = change_to_goodbye() 

     self.helloWorld.define_hello() 
     self.changeToGoodbye.hello_to_goodbye() 
     self.helloWorld.say_hello() 

oc = other_class() 

hello_world类有两种方法,一种定义变量hello和一个用于打印它。另一方面,change_to_goodbye类尝试访问类hello_world中的变量hello,并将其更改为goodbye。类other_class应将变量hello设置为“hello”,将其更改为“goodbye”,并将其打印在屏幕上。

我预计输出是“再见”,但我得到了“你好”。为什么change_to_goodbye更改hello_world的变量?

回答

2

这是因为您的change_to_goodbye类在其中存储了自己的hello_world对象。 changeToGoodbye中的hello_world对象与hello_world对象helloWorld不同。所以在other_class当你做self.changeToGoodbye.hello_to_goodbye()时,你的helloWorld变量根本没有被改变。什么被改变是changeToGoodbye的helloWorld对象。

因此:self.changeToGoodbye.helloWorld.say_hello()会返回。

所以总结:

class other_class(): 
    def __init__(self): 
     self.helloWorld = hello_world() 
     self.changeToGoodbye = change_to_goodbye() #contains a different hello_world object 

     self.helloWorld.define_hello() 
     self.changeToGoodbye.hello_to_goodbye() #changes the hello_world object inside of changeToGoodbye 
     self.helloWorld.say_hello() #the unaltered helloWorld object 

,如果你想改变的helloWorld输出,使其程序hello_world对象是刚刚创建的一个,你可以改变change_to_goodbye类的构造函数。

class change_to_goodbye(): 
    def __init__(self, hw): 
      self.helloWorld = hw 

    #other code 
+0

虽然'change_to_goodbye'可以直接改变'hello_world'类中的变量吗? – Tetsudou 2014-10-09 02:42:27

+0

它改变了hello_world中的变量,它只是改变了hello_world变量的不同实例。你想要做的是存储你在change_to_goodbye类中创建的hello_world对象。这可以通过以我在答案底部显示的方式改变构造函数来完成 – xgord 2014-10-09 02:44:28

1

你不改变类变量,你正在改变实例变量。

通过self.helloWorld = hello_world()你定义了一个hello_world实例,让我们把它称为一个,并self.changeToGoodbye = change_to_goodbye()你定义change_to_goodbye例如它有一个hello_world例如Ç

self.helloWorld.define_hello()然后设置的变量作为你好self.changeToGoodbye.hello_to_goodbye()设置Ç的变量作为再见

最后self.helloWorld.say_hello()会打印出A的变量,您将得到hello