Wie kann eine globale Variable mit Klassenbereich in Python richtig definiert werden?
Aus einem C/C++/Java-Hintergrund kommend gehe ich davon aus, dass dies korrekt ist:
class Shape:
lolwut = None
def __init__(self, default=0):
self.lolwut = default;
def a(self):
print self.lolwut
def b(self):
self.a()
Was Sie haben, ist korrekt, obwohl Sie es nicht global nennen, es ist ein Klassenattribut und kann über eine Klasse, z. B. Shape.lolwut
Oder über eine Instanz, z. shape.lolwut
Aber seien Sie vorsichtig, wenn Sie es einstellen, da es ein Attribut auf Instanzebene und kein Klassenattribut setzt
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
ausgabe:
1 1 1 2 3 2
Jemand könnte erwarten, dass die Ausgabe 1 1 2 2 3 3
Ist, aber das wäre falsch