使用len()和def __len __(self):建立一个类 [英] Using len() and def __len__(self): to build a class
问题描述
很好奇,
在构建类时,使用len()
或def __len__()
有什么区别(优点和缺点)?最好的Python风格是什么?
Is there any difference (advantages and disadvantages) between using len()
or def __len__()
when I build a class? And which is the best Python style?
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__()
方法是挂钩方法. len()
函数将使用__len__
方法(如果存在)来查询对象的长度.
The __len__()
method is a hook method. The len()
function will use the __len__
method if present to query your object for it's length.
人们期望使用的 normal API是len()
方法,而使用.len
属性会偏离该规范.
The normal API people expect to use is the len()
method, using a .len
attribute instead would deviate from that norm.
如果预计self.data
的长度不会改变,则始终可以将长度缓存在属性中,并让.__len__()
返回该属性.
If the length of self.data
is not expected to change, you can always cache the length in an attribute and have .__len__()
return that attribute.
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
这篇关于使用len()和def __len __(self):建立一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!