python - 使用 len() 和 def __len__(self) : to build a class

标签 python class optimization coding-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)

   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/

相关文章:

java - 如何访问java属性文件

python - Selenium 中发现元素的顺序

python - 如何在scrapy中挖掘链接中的站点

c++ - 如何为具有私有(private)对象作为属性的类编写移动构造函数和赋值运算符?

Java swing 渲染优化

javascript - 如何在 V8 中优化访问时间的小型对象引用数组?

optimization - IBM XL C/C++ 等效于 #pragma GCC 优化

python - 如何使用 `input_fn` 和 `read_batch_examples` 设置来创建 `num_epochs`?

python - 如何向Python中现有的类添加方法?

c++ - 具有相同概念的类(class)过多