我希望在我的類中實作一個自定義方法,以幫助用戶根據索引進行切片。主切片將基于字典鍵。我想實作它類似于 Pandas 的做法,使用df.iloc[n]
這是我的代碼:
class Vector:
def __init__(self, map_object: dict):
self.dictionary = map_object
def __getitem__(self, key):
data = self.dictionary[key]
return data
def iloc(self, n):
key = list(self.dictionary)[n]
return self.dictionary[key]
但是,如果object.iloc[3]在創建物件后寫入,我會收到一條錯誤訊息'method' object is not subscriptable。那么我該如何實作呢?
uj5u.com熱心網友回復:
[ ]語法需要帶有方法的適當物件__getitem__。為了有一個“切片方法”,使用一個property回傳一個支持切片的助手。
助手簡單地持有對實際parent物件的參考,并__getitem__用所需的行為定義 a:
class VectorIloc:
def __init__(self, parent):
self.parent = parent
# custom logic for desired "iloc" behaviour
def __getitem__(self, item):
key = list(self.parent.dictionary)[item]
return self.parent[key]
在實際類中,只需將所需的“方法”定義為property回傳幫助程式的 a 或屬性:
class Vector:
def __init__(self, map_object: dict):
self.dictionary = map_object
# if .iloc is used often
# self.iloc = VectorIloc(self)
def __getitem__(self, key):
return self.dictionary[key]
# if .iloc is used rarely
@property
def iloc(self):
return VectorIloc(self)
是否使用 aproperty或屬性是一種以記憶體換性能的優化:屬性始終構造和存盤幫助器,而 aproperty僅按需構造它,但在每次訪問時構造它。Afunctools.cached_property可以用作中間立場,在首次訪問時創建屬性。當每個物件很少使用助手時,特別是如果它經常根本不使用時,
這是有利的。property
現在,當呼叫 時vector.iloc[3],該vector.iloc部分提供了助手,而該[3]部分呼叫了助手的__getitem__。
>>> vector = Vector({0:0, 1: 1, 2: 2, "three": 3})
>>> vector.iloc[3]
3
uj5u.com熱心網友回復:
我一直在尋找我在 Pandas 中非常習慣的實作。但是,經過大量搜索,我找不到任何合適的答案。所以我瀏覽了 Pandas 源代碼,發現實作它的主要要求如下:
- 使用裝飾器創建方法
@property,使其接受切片物件而不拋出上述錯誤 - 創建第二個類根據索引進行切片,將self傳給這個類,從方法中回傳這個類
我的最終代碼最終看起來像這樣:
class TimeSeries:
def __init__(self, data: dict):
self.data = data
def __getitem__(self, key):
data = self.data[key]
return data
@property
def iloc(self):
return Slicer(self)
class Slicer:
def __init__(self, obj):
self.time_series = obj
def __getitem__(self, n):
key = list(self.time_series.data)[n]
return self.time_series[key]
使用這種方式定義的類,我可以撰寫以下代碼:
>>> ts = TimeSeries({'a': 1, 'b': 2, 'c': 3, 'd': 4})
>>> print("value of a:", ts['a'])
value of a: 1
>>> print("value at position 0:", ts.iloc[0])
value at position 0: 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429188.html
標籤:Python python-3.x
