我想用python3編寫一個自定義列表類,就像在這個問題How would I create a custom list class in python?中一樣,但與該問題不同,我想實現__get__和{}方法。雖然我的類與list類似,但是這些方法背后隱藏著一些神奇的操作。所以我想處理這個變量,比如list,比如我程序的main(見下文)。我想知道,如何將__get__和__set__方法(分別是fget和{})從Foo類移動到{}類,從而只有一個類。在
我當前的解決方案(為了清晰起見,我還為每個操作添加了輸出):class MyList:
def __init__(self, data=[]):
print('MyList.__init__')
self._mylist = data
def __getitem__(self, key):
print('MyList.__getitem__')
return self._mylist[key]
def __setitem__(self, key, item):
print('MyList.__setitem__')
self._mylist[key] = item
def __str__(self):
print('MyList.__str__')
return str(self._mylist)
class Foo:
def __init__(self, mylist=[]):
self._mylist = MyList(mylist)
def fget(self):
print('Foo.fget')
return self._mylist
def fset(self, data):
print('Foo.fset')
self._mylist = MyList(data)
mylist = property(fget, fset, None, 'MyList property')
if __name__ == '__main__':
foo = Foo([1, 2, 3])
# >>> MyList.__init__
print(foo.mylist)
# >>> Foo.fget
# >>> MyList.__str__
# >>> [1, 2, 3]
foo.mylist = [1, 2, 3, 4]
# >>> Foo.fset
# >>> MyList.__init__
print(foo.mylist)
# >>> Foo.fget
# >>> MyList.__str__
# >>> [1, 2, 3, 4]
foo.mylist[0] = 0
# >>> Foo.fget
# >>> MyList.__setitem__
print(foo.mylist[0])
# >>> Foo.fget
# >>> MyList.__getitem__
# >>> 0
提前謝謝你的幫助。在
如何將__get__和__set__方法(分別是fget和fset)從Foo類移動到MyList類,從而只有一個類?在
升級版:
非常感謝@Blckknght!我試著去理解他的答案,這對我很有效!這正是我所需要的。因此,我得到了以下代碼:
^{pr2}$
我不知道,這是不是Python的方式,但它的工作方式如我所料。在