__len__(self)
时间: 2023-07-31 09:09:15 浏览: 59
`__len__(self)` is a special method in Python classes that returns the length of an object. It is used to implement the built-in `len()` function for custom objects. By defining this method in a class, you can specify how the object should be considered in terms of length.
Here's an example implementation of `__len__` method in a class:
```python
class MyClass:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
my_object = MyClass([1, 2, 3, 4, 5])
print(len(my_object)) # Output: 5
```
In this example, the `__len__` method is defined to return the length of the `data` attribute of the `MyClass` object. When `len()` is called on `my_object`, it will invoke the `__len__` method and return the length of the data list.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)