当定义class
时(ex. class MyClass
),可以将其返回的内容替换为len (my_class_instance)
使用 def __len__(self)
。
如何将其应用于下面的自定义
类
@property
场景?class CarWash(object): def __init__(self): self._queue = [1, 2, 3] @property def queue(self): return self._queue
当调用len(car_wash.queue)
时,我不希望返回列表的len,但想用自定义的__len__
过程替换它,因为我想先查询数据库。
我该怎么做?
最佳答案
如果您不想调用 list.__len__
,请不要返回列表:
def CarQueue(list):
def __len__(self):
return something_dubious()
# if you're going to override len, make sure to overide `__iter__`
# and `__getitem__`
class CarWash(object):
def __init__(self):
self._queue = CarQueue([1, 2, 3])
@property
def queue(self):
return self._queue
关于python - 如何用自定义 __len__() 过程替换类 @property 的 len(..) 返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17818208/