top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

How can I overload constructors (or methods) in Python?

+1 vote
88 views
How can I overload constructors (or methods) in Python?
posted Dec 4, 2014 by Amit Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

This answer actually applies to all methods, but the question usually comes up first in the context of constructors.

In C++ you’d write

class C {
    C() { cout << "No arguments\n"; }
    C(int i) { cout << "Argument is " << i << "\n"; }
}

in Python you have to write a single constructor that handles all cases, using either default arguments or type or capability tests. For example:

class C:
    def __init__(self, i=None):
        if i is None:
            print "No arguments"
        else:
            print "Argument is", i

This is not entirely equivalent, but close enough in practice.

You could also try a variable-length argument list, e.g.

def __init__(self, *args):

The same approach works for all method definitions.

answer Dec 29, 2014 by Kali Mishra
Similar Questions
+2 votes

I have a multi-line string and I need to remove the very first line from it. How can I do that? I looked at StringIO but I can't seem to figure out how to properly use it to remove the first line.

0 votes

I want to create a random float array of size 100, with the values in the array ranging from 0 to 5. I have tried random.sample(range(5),100) but that does not work. How can i get what i want to achieve?

+1 vote

i want to create a chrome extension. its have complex mathematical queries. so i need to use python as scripting language. help me to implement python script in google chrome addon

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...