Python 使用 len() 和 def __len__(self): 来构建一个类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15114023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:22:25  来源:igfitidea点击:

Using len() and def __len__(self): to build a class

pythonclassoptimizationcoding-style

提问by Gianni Spear

Just curious,

只是好奇,

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?

使用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)

or

或者

   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)

采纳答案by Martijn Pieters

There is a hugedifference.

很大的不同。

The __len__()method is a hook method. The len()functionwill use the __len__method if present to query your object for it's length.

__len__()方法是一个钩子方法。该len()函数将使用该__len__方法(如果存在)来查询您的对象的长度。

The normalAPI people expect to use is the len()method, using a .lenattribute instead would deviate from that norm.

人们期望使用的正常API 是len()方法,而使用.len属性会偏离该规范。

If the length of self.datais not expected to change, you can always cache the length in an attribute and have .__len__()return that attribute.

如果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

回答by NPE

There are several differences:

有几个区别:

  1. Only the second approach will give you the familiar len(obj)syntax for foo. The first will require obj.len().
  2. If the length of self.datacan change post-construction, only the second version will reflect the new length.
  1. 只有第二种方法才能为您提供熟悉len(obj)foo. 第一个将需要obj.len().
  2. 如果self.data构建后的长度可以更改,则只有第二个版本会反映新的长度。