While handling the database connection I used the singleton pattern for the evident reason. for simplification purposes, I have simplified the class definition, the problem is still the same.
the class:
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))
it generates the following error:
AttributeError: 'Point' object has no attribute '_x'
I have found the following workaround:
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
The pythonic way is to use property method, hence I still have that itch, even though I have a working code, can someone explain to me why-why I have such an error.