说我有这样的代码:在从其他类(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
的变量?
虽然'change_to_goodbye'可以直接改变'hello_world'类中的变量吗? – Tetsudou 2014-10-09 02:42:27
它改变了hello_world中的变量,它只是改变了hello_world变量的不同实例。你想要做的是存储你在change_to_goodbye类中创建的hello_world对象。这可以通过以我在答案底部显示的方式改变构造函数来完成 – xgord 2014-10-09 02:44:28