本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Python: Difference between class and instance attributes
我试图在Python中了解OOP,当它在类中声明变量时,我有点困惑。我应该在__init__程序内部还是外部申报?有什么区别?
以下代码工作正常:
# Declaring variables within __init__
class MyClass:
def __init__(self):
country =""
city =""
def information(self):
print"Hi! I'm from %s, (%s)"%(self.city,self.country)
me = MyClass()
me.country ="Spain"
me.city ="Barcelona"
me.information()
但是在__init__过程之外声明变量也有效:
# Declaring variables outside of __init__
class MyClass:
country =""
city =""
def information(self):
print"Hi! I'm from %s, (%s)"%(self.city,self.country)
me = MyClas