There are different things that you could be trying to do, and you probably need to research a little bit more about python itself, but let's see if this helps:
If you want to have a class whose instances share a common response, you can have something like this:
class XYZ(object):
response = "Hi Pranjal!"; # class atribute
def change_talk(self, response):
# class methods always get `self` (the object through which they are
# called) as their first argument, and it's commons to call it `self`.
XYZ.response = response # change class atribute
def talk(self):
print XYZ.response
XYZ_inst = XYZ() # instance of the class that will have the class methods
XYZ_inst.talk() # instance "talks"
#"Hi Pranjal!"
XYZ_inst.change_talk("Hi Anand!");
XYZ_inst.talk()
#"Hi Anand!"
XYZ_inst_2 = XYZ()
## New instance has the same response as the previous one:
XYZ_inst_2.talk()
#"Hi Anand!"
## And changing its response also changes the previous:
XYZ_inst_2.change_talk("Hi Bob!")
XYZ_inst_2.talk()
#"Hi Bob!"
XYZ_inst.talk()
#"Hi Bob!"
On the other hand, if you want each instance to have its own response (see more about __init__
):
class XYZ2(object):
# you must initialise each instance of the class and give
# it its own response:
def __init__(self, response="Hi Pranjal!"):
self.response = response
def change_talk(self, response):
self.response = response;
def talk(self):
print self.response
XYZ_inst = XYZ2() # object that will have the class methods
XYZ_inst.talk()
#"Hi Pranjal!"
XYZ_inst.change_talk("Hi Anand!");
XYZ_inst.talk()
#"Hi Anand!"
XYZ_inst_2 = XYZ2()
## new instance has the default response:
XYZ_inst_2.talk()
#"Hi Pranjal!"
## and changing it won't change the other instance's response:
XYZ_inst_2.change_talk("Hi Bob!")
XYZ_inst_2.talk()
#"Hi Bob!"
XYZ_inst.talk()
#"Hi Anand!"
Finally, if you really want to have a global variable (which is not really advised as for changing whatever is outside the class instance you should pass it as an argument to the method changing it):
# global variable created outside the class:
g_response = "Hi Pranjal!"
class XYZ3(object):
def change_talk(self, response):
# just declare you are talking with a global variable
global g_response
g_response = response # change global variable
def talk(self):
global g_response
print g_response
XYZ_inst = XYZ3() # object that will have the class methods
XYZ_inst.talk()
#"Hi Pranjal!"
XYZ_inst.change_talk("Hi Anand!");
XYZ_inst.talk()
#"Hi Anand!"
print g_response
#"Hi Anand!"