0

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

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

well, the problem is that I need to have both the copy constructor and the standart constructor
You can't have two init methods. You can try with the None value as I initially suggested and then inside the constructor you can check: if human is None: ... else: ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.