还有,你可以尝试做不同的事情,你可能需要research a little bit more关于Python本身,而是让我们看看这可以帮助:如果你想有一个类,其实例都有一个共同的响应
,你可以有这样的事情:
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!"
在另一方面,如果你想每个实例有它自己的响应(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!"
最后,如果你真的想有一个global variable(这是not really advised为改变无论是类的实例之外,你应该把它作为参数传递给方法变更的话):
# 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!"
是您的空白完全一样在问题中给出? – doctorlove
是的,缩进是正确的。 – Pranzell
为什么你有班级的代码?看到你在每行中都有不需要的尾部分号,我可以放心地认为你是Python的新手。我认为你在这里有一个错误的方法。请解释你真正想做的事情。顺便说一下,“响应”不是全球性的。 – Matthias