Was ist der Unterschied zwischen der Deklaration von Datenattributen innerhalb oder außerhalb von __init__ [Duplikat]Python

Python-Programme
Anonymous
 Was ist der Unterschied zwischen der Deklaration von Datenattributen innerhalb oder außerhalb von __init__ [Duplikat]

Post by Anonymous »

Ich versuche mich mit OOP in Python vertraut zu machen und bin etwas verwirrt, wenn es darum geht, Variablen innerhalb einer Klasse zu deklarieren. Soll ich sie innerhalb der Prozedur __init__ deklarieren oder außerhalb? Was ist der Unterschied?
Der folgende Code funktioniert einwandfrei:

Code: Select all

# 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()
Aber die Deklaration der Variablen außerhalb der __init__-Prozedur funktioniert auch:

Code: Select all

# 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()

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post