How to specify argument type in a dynamically typed language, i.e. Python?

后端 未结 5 1638
甜味超标
甜味超标 2021-01-23 13:11

Is there any such equivalent of Java

String myMethod (MyClass argument) {...}

in Python?

Thank you, Tomas

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-23 13:29

    No.

    In Python, it's the program's responsibility to use built-in functions like isinstance() and issubclass() to test variable types and correct usage. Python tries to stay out of your way while giving you all you need to implement strong type checking.

    from Why is Python a dynamic language and also a strongly typed language. Also

    In a dynamically typed language, a variable is simply a value bound to a name; the value has a type -- like "integer" or "string" or "list" -- but the variable itself doesn't. You could have a variable which, right now, holds a number, and later assign a string to it if you need it to change.

    Further, isinstance() and issubclass() can be used to do type-checking. If you want to make sure that argument is of MyClass type, you can have a check inside the function. You can even type-cast the value of the argument (if you have a constructor accepting such value) and assign it to my_object.

提交回复
热议问题