Während der Behandlung der Datenbankverbindung verwendete ich das Singleton-Muster aus dem offensichtlichen Grund. Zur Vereinfachung habe ich die Klassendefinition vereinfacht, das Problem ist immer noch das gleiche.Attributfehler, Singleton-Muster mit Eigenschaftsmethode
die Klasse:
class Point(object):
_instance = None
def __new__(cls, x, y):
if Point._instance is None:
Point._instance = object.__new__(cls)
Point._instance.x = x
Point._instance.y = y
return Point._instance
def __init__(self, x, y):
self.x = x
self.y = y
@property
def x(self):
return self._x
@x.setter
def x(self, x):
self._x = self._instance.x
@property
def y(self):
return self._y
@y.setter
def y(self, y):
self._y = self._instance.y
def __str__(self):
return 'x: {}, y: {} id.x: {}'.format(self.x, self.y, id(self.x))
es erzeugt folgende Fehler:
AttributeError: 'Point' object has no attribute '_x'
I die folgende Abhilfe gefunden:
class Point(object):
_instance = None
def __new__(cls, x, y):
if Point._instance is None:
Point._instance = object.__new__(cls)
Point._instance.x = x
Point._instance.y = y
return Point._instance
def __init__(self, x, y):
self.x = self._instance.x
self.y = self._instance.y
Die pythonic Weise Eigenschaft Methode zu verwenden, daher habe ich immer noch das Jucken, obwohl ich einen funktionierenden Code habe, kann mir jemand erklären, warum - warum ich habe so ein Fehler.
Die Vertiefung. Es schmerzt. – jq170727
Warum möchten Sie, dass eine Point-Klasse ein Singleton ist ?! – wim
@ jq170727 Ich habe nicht auf die Einrückung geachtet, sorry, ich habe gerade den Code von meinem Editor. –