在处理数据库连接时,出于明显的原因,我使用了单例模式。为了简化目的,我简化了类的定义,问题仍然是一样的。属性错误,具有属性方法的单身模式
类:
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))
它生成以下错误:
AttributeError: 'Point' object has no attribute '_x'
我已经发现了以下解决方法:
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
的Python的方式是使用属性的方法,因此即使我有一个工作代码,我仍然有这种痒,有人可以向我解释为什么 - 我为什么这样的错误。
缩进。好痛。 – jq170727
为什么你想要一个Point类是单身人士? – wim
@ jq170727我没有注意到缩进对不起,我只是从我的编辑过去的代码。 –