OOP: force the type of an object

class Pokemon:
def init(self, name: str = “-”, type: str = ‘-’, age : int = ‘-’):
self.name = name
self.type = type
self.age = age
def presentation(self):
print(f’Type of {self.name} : {self.type}\nAge of {self.name} : {self.age}')

pikachu = Pokemon(‘Pikachu’, “electric”)

Charizard = Pokemon(‘Charizard’, 12)

Output for Charizard :

Type of Charizard : 12
Age of Charizard : -

Please, how force the type of an object ?

I think what you’re looking for is named arguments:

Charizard = Pokemon(‘Charizard’, age=12)

But I’m not completely sure this is what you’re looking for.

EDIT: Ah, no, I think you’re wondering why the type annotation isn’t enforced. Well, Python is a dynamically typed language so there is no enforcement of annotations but you can use static type checkers to to check whether the types are all correct in your code.

EDIT2: Thinking about it even more, I think what you’re looking for is a mechanism to pick an overload of a function based on the type of the supplied arguments. You can use @singledispatch for this from the standard library. But it’s honestly pretty rarely used. I think the correct solution is with the named argument that I had above.

Use of the string ‘-’ to mean not set is not typical in python.
The typical use is to use None to mean not set.

Also please put your code in side code-fences the </> icon or type

class Pokemon:
    def init(self, name: str=None, type: str=None, age : int=None):

But I suspect that you must provide the name and type so you would write:

class Pokemon:
    def init(self, name: str, type: str, age : int=None):

When printing you would check for the None like this:

def presentation(self):
    print(f’Type of {self.name} : {self.type}')
    if self.age is not None:
        print(f'Age of {self.name} : {self.age}')

Personally I would not embed a \n inside a print.
I would use one print call for each line. I fine that easier to read.

The easiest way is by using Pydantic UserBase classes. Add a type hint and Pydantic does all the heavy lifting for you.