Harton
Harton

Reputation: 116

working around the fact that python can't make more than one constructor

I have these classes:

class Human:
    def __init__(self, x_position, y_position): 
        self.y_position = y_position
        self.x_position = x_position

class Feared(Human):
    def __init__(self, x_position=0, y_position=0, fear_percent=0): 
        self.y_position = y_position
        self.x_position = x_position
        self.fear_percent=fear_percent

Greetings, so I have these classes, I want to make a couple of Human objects and after that I want to transform them into Feared objects. How do you generally solve this problem? In C++ I could refedine the = operator, can I do this in Python? Or I could create a constructor/function which has specified argument types. But here variables are specified when adding them in the arguments of the function. So can I make two init functions, one which has one arg type human and the other one which I have already created ?

So how do you workaround the fact that python can't make more than one constructor

Upvotes: 0

Views: 78

Answers (2)

Gribouillis
Gribouillis

Reputation: 2220

In C++, you don't transform Human objects into Feared objects, the same usually holds in python. What you can do is create a new Feared object from a single Human parameter.

There can be only one __init__() method in a class. Among the possible solutions one can add a class method in Feared object:

class Feared(Human):
    ....
    @classmethod
    def from_human(cls, hum):
        return cls(hum.x_position, hum.y_position, 0)

h = Human(4, 4)
feared = Feared.from_human(h)

Upvotes: 1

Dimitar Hristov
Dimitar Hristov

Reputation: 133

No,you can't have multiple constructors in python. You can try and include a reference of type Human in the constructor that you currently have and set it to be equal to None. In this way if you don't pass a Human object, it will be None by default.

Upvotes: 0

Related Questions