Reputation: 224
Say I have this code:
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()
Class hello_world
has two methods, one that defines the variable hello
and one that prints it. On the other hand, class change_to_goodbye
tries to access the variable hello
in class hello_world
and changes it to goodbye
. Class other_class
should set the variable hello
to "hello", change it to "goodbye", and print it on the screen.
I expected the output to be "goodbye" but I got "hello". Why isn't change_to_goodbye
changing the variable of hello_world
?
Upvotes: 0
Views: 116
Reputation: 7255
You are not changing class variable, you are changing instance variable.
By self.helloWorld = hello_world()
you defines an hello_world
instance let's called it A, and self.changeToGoodbye = change_to_goodbye()
you defines an change_to_goodbye
instance B which has an hello_world
instance C.
Then self.helloWorld.define_hello()
set A's variable as hello and self.changeToGoodbye.hello_to_goodbye()
set C's variable as goodbye.
At last self.helloWorld.say_hello()
will print A's variable, and you will get hello.
Upvotes: 1
Reputation: 4776
This is because your change_to_goodbye
class stores its own hello_world
object inside it. The hello_world
object in changeToGoodbye
is not the same as the hello_world object helloWorld
. So in other_class
when you do self.changeToGoodbye.hello_to_goodbye()
, your helloWorld variable isn't being altered at all. What's being altered is changeToGoodbye's helloWorld object.
So: self.changeToGoodbye.helloWorld.say_hello()
would return goodbye.
So to summarize:
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
if you wanted to change the output of helloWorld
, you could change the change_to_goodbye class's constructor so that its hello_world object is the one you just created.
class change_to_goodbye():
def __init__(self, hw):
self.helloWorld = hw
#other code
Upvotes: 2