Learn more about the special function __len__(self) in python

零下一度
Release: 2017-05-23 14:49:32
Original
2836 people have browsed it

len If a class behaves like a list, to get the number of elements, you have to use the len() function. For the len() function to work properly, the class must provide a special method len(), which returns the number of elements.
For example, we write a Students class and pass the name in:

class Students(object):    def init(self, *args):
        self.names = args    def len(self):        return len(self.names)
Copy after login

As long as the len() method is correctly implemented, you can use the len() function to return the "length" of the Students instance:

>>> ss = Students('Bob', 'Alice', 'Tim')>>> print len(ss)3
Copy after login

Task
The Fibonacci sequence is composed of 0, 1, 1, 2, 3, 5, 8....
Please write a Fib class. Fib(10) represents the first 10 elements of the sequence. print Fib(10) can print out the first 10 elements of the sequence. len(Fib(10)) can correctly return the number of the sequence. 10.

Need to calculate the first N elements of the Fibonacci sequence based on num.
Reference code:

class Fib(object):    def init(self, num):
        a, b, L = 0, 1, []        for n in range(num):
            L.append(a)
            a, b = b, a + b
        self.numbers = L    def str(self):        return str(self.numbers)    repr = str
    def len(self):        return len(self.numbers)
f = Fib(10)print fprint len(f)
Copy after login

List can only insert elements through append and insert! ! !

【Related Recommendations】

1. Summary of usage examples of len() function in Python

2. Must master Little knowledge--Detailed explanation of Python len examples

3. An example tutorial on the use of python special class methods

4. Python magic methods __getitem__, __setitem__, __delitem__, __len__ are introduced respectively

The above is the detailed content of Learn more about the special function __len__(self) in python. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template