Multiple constructors in python, using inheritance

前端 未结 3 1782
走了就别回头了
走了就别回头了 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

    You can use class methods, which work as factory methods. That's imho the best approach for multiple constructors. First argument 'cls' is class itself, not it's instance, so cls('Truck') in class method invokes constructor for class Car.

    class Car(object):
        def __init__(self, type='car'):
            self.car_type = type
    
        @classmethod
        def Truck(cls):
            return cls('Truck')
    
        @classmethod
        def Sport(cls):
            return cls('Sport')
    
        @classmethod
        def Van(cls):
            return cls('Van')
    

    Then you call factory method this way:

    mycar = Car.Sport()
    

提交回复
热议问题