@property
(長所と短所)の使用については明確ではありません。Martijnの助けを借りて構築されたこのクラスを使用して、いくつかの例を求めたいと思います。
データ (テキスト形式) には、点 (テキスト ファイルの 1、2、および 3 列) を特徴付けるx
、y
、およびが常に含まれます。z
" classification
" (4 列目) 属性および/または location
(5 列目) がある場合があります。ファイルの処理方法によって異なります (場合によっては、より多くの属性)。
class Point(object):
__slots__= ("x", "y", "z", "data", "_classification")
def __init__(self, x, y, z):
self.x = float(x)
self.y = float(y)
self.z = float(z)
self.data = [self.x,self.y,self.z]
@property
def classification(self):
return getattr(self, '_classification', None)
@classification.setter
def classification(self, value):
self._classification = value
if value:
self.data = self.data[:3] + [value]
else:
self.data = self.data[:3]
def __len__(self):
return len(self.data)
p = Point(10,20,30)
len(p)
3
p.classification = 1
len(p)
4
p.data
[10.0, 20.0, 30.0, 1]
を使用する哲学を理解するために、location
whenが既に設定されている場合を追加したいと思います。次のコードを試してみましたが、これがpythonicかどうかわかりません:classification
@property
class Point(object):
__slots__= ("x", "y", "z", "data", "_classification",'_location')
def __init__(self, x, y, z):
self.x = float(x)
self.y = float(y)
self.z = float(z)
self.data = [self.x,self.y,self.z]
@property
def classification(self):
return getattr(self, '_classification', None)
@classification.setter
def classification(self, value):
self._classification = value
if value:
self.data = self.data[:3] + [value]
else:
self.data = self.data[:3]
@property
def location(self):
return getattr(self, '_location', None)
@location.setter
def location(self, value):
self._location = value
if value:
self.data = self.data[:4] + [value]
else:
self.data = self.data[:4]
def __len__(self):
return len(self.data)
p = Point(10,20,30)
p.classification = 1
p.data
[10.0, 20.0, 30.0, 1]
p.location = 100
p.data
[10.0, 20.0, 30.0, 1, 100]
p = Point(10,20,30)
p.location = 100
p.data
[10.0, 20.0, 30.0, 100]