Home > Mobile >  How to define class for input variable in VS Code
How to define class for input variable in VS Code

Time:07-27

I'm learning python, suppose I have a class and want to use it as a input variable for other defs:

class person:
    def get_name(self):
        return self.name
    def set_name(self):
        self.name = name

def dummy(p):
    print(p.get_name())

How to tell the IDE know p is an instance of the class person and suggest the defs of the person like Java. Thanks you.

CodePudding user response:

Use type hints.

class Person:
    def get_name(self):
        return self.name
    def set_name(self):
        self.name = name

def dummy(p: Person):
    print(p.get_name())

look up type hints on google and you could research them a bit if you wanted to

CodePudding user response:

Consider using a type hint. These are classes you can suggest a certain value will be. Consider this

def say_hello(name: str, age: int) -> None:
    message: str = f'Hello, {name}! You are {age} years old'
    print(message)

Here, we say a function say_hello will take two args: name, which should be an instance of the str class, and age, which should be an instance of the int class. The function should return None, and it defines a local variable message which should also be a string.

Notice how each time I said "should". Python is a dynamically-typed language, so none of these will cause an error if their values aren't instances of the specified class. These are just a peak at what the variables should be for the developer.

  • Related