Learn more about special functions in Python __len__ (self)

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.