Multiple constructors in python, using inheritance

前端 未结 3 1779
走了就别回头了
走了就别回头了 2020-12-15 09:09

I have a class AbstractDataHandle, whith his init method, and a class Classifier. I would like to have two constructors in Classifier, Java like. One inheri

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 09:48

    There are the methods in the accepted answer, but I think this one is fairly flexible. It's convoluted, but very flexible.

    When the class is instiated, init calls a method and pass it a string argument (obtained from instantiation). That function uses conditionals to call the right "constructor" function to initialize your values, let's say you have different sets of possible starting values.

    If you need to provide other arguments (e.g. that might have a value only at runtime), you can use default values in init() to allow optional arguments, and initialize those in init as you normally would.

    class MyClass:
    def __init__(self,argsSet1, otherAttribute="Assigning this default value 
                 to make this other argument optional",):
        self.selectArgSet(argsSet1)
        self.otherAttribute = otherAttribute
        print otherAttribute
    def selectArgSet(self,ArgSet1):
        if ArgSet1 == "constructorArgSet1":
            self.constructorArgSet1()
        elif ArgSet1 == "constructorArgSet2":
            self.constructorArgSet2()
    def constructorArgSet1(self):
        print "Use this method as Constructor 1"
        self.variable1 = "Variable1 value in Constructor 1"
        self.variable2 = "Variable2 value in Constructor 1"
        print self.variable1
        print self.variable2
    def constructorArgSet2(self):
        print "Use this method as Constructor 2"
    
    
          self.variable1 = "Variable1 value in Constructor 2"
            self.variable2 = "Variable2 value in Constructor 2"
            print self.variable1
            print self.variable2
    
    myConstructor_1_Instance = MyClass("constructorArgSet1")
    myConstructor_2_Instance = MyClass("constructorArgSet2", "You can still 
                                               initialize values normally")
    

    The output of which is:

    Use this method as Constructor 1

    Variable1 value in Constructor 1

    Variable2 value in Constructor 1

    Assign default value to make this other argument optional

    Use this method as Constructor 2

    Variable1 value in Constructor 2

    Variable2 value in Constructor 2

    You can still initialize values normally

提交回复
热议问题