只是好奇,
在构建类时使用 len()
或 def __len__()
有什么区别(优点和缺点)?哪种 Python 风格最好?
class foo(object):
def __init__(self,obs=[])
self.data = obs
self.max = max(obs)
self.min = min(obs)
self.len = len(obs)
或
class foo(object):
def __init__(self,obs=[])
self.data = obs
self.max = max(obs)
self.min = min(obs)
def __len__(self):
return len(self.data)
最佳答案
有一个巨大的差异。
__len__()
方法是一个钩子(Hook)方法。 len()
function 将使用 __len__
方法(如果存在)来查询对象的长度。
人们期望使用的正常 API 是len()
方法,而使用.len
属性会偏离该规范。
如果 self.data
的长度预计不会改变,您始终可以将长度缓存在属性中并让 .__len__()
返回该属性。
class foo(object):
def __init__(self, obs=None):
if obs is None: # provide a default if no list was passed in.
obs = []
self.data = obs
self.max = max(obs)
self.min = min(obs)
self._data_len = len(obs)
def __len__(self):
return self._data_len
关于python - 使用 len() 和 def __len__(self) : to build a class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15114023/