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

后端 未结 2 1429
栀梦
栀梦 2020-12-29 02:59

Just curious,

Is there any difference (advantages and disadvantages) between using len() or def __len__() when I build a class? And which i

2条回答
  •  感情败类
    2020-12-29 03:37

    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.data can change post-construction, only the second version will reflect the new length.

提交回复
热议问题