constructor overloading like Java ?

jmdeschamps jmdeschamps at cvm.qc.ca
Mon May 26 12:29:21 EDT 2003


Markus Jais <mjais at web.de> wrote in message news:<cpmAa.2$1f6.2786 at news.ecrc.de>...
> hello
> 
> can something like this be done in Python ?
> 
> _______________________________________________
> class MyObject
> {
>           public MyObject()
>           {
>                  System.out.println("uno");
>           }
> }
> 
> class MyClass
> {
>           private int a;
>           private MyObject my;
> 
>           public MyClass(int a)
>           {
>                  this.a = a;
>           }
> 
>           public MyClass(MyObject my)
>           {
>                  this.my = my;
>           }
>           
> }
> 
> 
> class MyTest
> {
> 
>           public static void main(String args[])
>           {
> 
>                  MyClass mc1 = new MyClass(42);
>                  MyClass mc2 = new MyClass(new MyObject());
>           }
> }
> __________________________________________
> 
> I want several constructors who expect different types
> of arguments.
> maybe I could use default Arguments but this is not possible if 
> I want a lot of more constructors with different parameters.
> 
> how could I do something similar in Python ??
> 
> Markus

Hi Markus,

Since Python variable are dynamically typed, you do your own type
checking maybe like this
#-- START ---
class MyObject:
    def __init__(self):
        print ("uno")

class MyClass:
    def __init__(self,a=None):
        self.a = None
        self.myObject = None
        # Check type here
        if type(a).__name__=="instance":
            self.myObject = a
        else:
            self.a = a

class MyTest:
    def __init__(self):
        mc1 = MyClass(2)
        mc2 = MyClass( MyObject())

if __name__ == "__main__"  :
    localTest = MyTest()
    # Added this to see it happen
    print "mc1.a is",mc1.a
    print "mc1.myObject is",mc1.myObject
    print "mc2.a is",mc2.a
    print "mc2.myObject is",mc2.myObject
#-- END --


NOTE if your type is 'instance', then use
someObject.__class__.__name__ to get the string-ed name of this class.

Hopes this helps,

Jean-Marc




More information about the Python-list mailing list