如何用删除器装饰列表
How to decorate a list with deleter
我正在为列表创建装饰器以设置、获取和删除值。但是 deleter
装饰器正在工作。当我调用 del object[key]
时,它实际上并没有按照我的预期进行 (print('dellllllll')
)。
class ListProperty:
def __init__(self) -> None:
self._l = []
@property
def l(self):
return self._l
@l.setter
def l(self, value):
self._l.append(value)
print('settttttttt')
@l.deleter
def l(self, key):
del self._l[key]
print('dellllllll')
ob = ListProperty()
print(ob.l)
ob.l = 5
print(ob.l)
ob.l = 100
print(ob.l)
del ob.l[0]
print(ob.l)
我在打电话时错过了什么del
你不能在删除时传递键,因为它需要一个参数而不是键。
您可以用另一种方式使用它:
class ListProperty:
def __init__(self) -> None:
self._l = []
@property
def l(self):
return self._l
@l.setter
def l(self, value):
self._l.append(value)
print('settttttttt')
@l.deleter
def l(self):
self._l = []
print('deleted all')
def pop(self, index):
self._l.pop(index)
print('dellllllll')
ob = ListProperty()
print(ob.l)
ob.l = 5
print(ob.l)
ob.l = 100
print(ob.l)
ob.pop(0)
print(ob.l)
del ob.l
print(ob.l)
我正在为列表创建装饰器以设置、获取和删除值。但是 deleter
装饰器正在工作。当我调用 del object[key]
时,它实际上并没有按照我的预期进行 (print('dellllllll')
)。
class ListProperty:
def __init__(self) -> None:
self._l = []
@property
def l(self):
return self._l
@l.setter
def l(self, value):
self._l.append(value)
print('settttttttt')
@l.deleter
def l(self, key):
del self._l[key]
print('dellllllll')
ob = ListProperty()
print(ob.l)
ob.l = 5
print(ob.l)
ob.l = 100
print(ob.l)
del ob.l[0]
print(ob.l)
我在打电话时错过了什么del
你不能在删除时传递键,因为它需要一个参数而不是键。
您可以用另一种方式使用它:
class ListProperty:
def __init__(self) -> None:
self._l = []
@property
def l(self):
return self._l
@l.setter
def l(self, value):
self._l.append(value)
print('settttttttt')
@l.deleter
def l(self):
self._l = []
print('deleted all')
def pop(self, index):
self._l.pop(index)
print('dellllllll')
ob = ListProperty()
print(ob.l)
ob.l = 5
print(ob.l)
ob.l = 100
print(ob.l)
ob.pop(0)
print(ob.l)
del ob.l
print(ob.l)