Я пытаюсь разобраться в ООП в Python и немного запутался, когда дело доходит до объявления переменных внутри класса. Должен ли я объявить их внутри процедуры __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 = MyClass()
me.country = "Spain"
me.city = "Barcelona"
me.information()
Подробнее здесь: https://stackoverflow.com/questions/138 ... utside-ini