Len if a class behaves like a list, you have to use the Len () function to get the number of elements. 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 that passes the name in:
Class Students (object): def init (self, *args): self.names = args def len (self): return Len (self.names )
As long as the Len () method is implemented correctly, you can return the "length" of the students instance using the Len () function:
>>> ss = Students (' Bob ', ' Alice ', ' Tim ') >>> print len (ss) 3
Task
The Fibonacci sequence is composed of 0, 1, 1, 2, 3, 5, 8 ...
Write a fib class where FIB (10) represents the first 10 elements of the sequence, print fib (10) Prints the first 10 elements of the array, and Len (Fib (10)) returns the number of numbers 10 correctly.
The first n elements of the Fibonacci sequence need to be calculated 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 (Ten) print Fprint len (f)
List can only be inserted by APPEND and insert!!!
"Recommended"
1. Summarize the use instances of the Len () function in Python
2. Required knowledge--python Len Example
3. Example Tutorials for using Python-specific class methods
4. Python Magic method __getitem__, __setitem__, __delitem__, __len__ respectively introduced