Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Python defines method parameter types, return value types, variable types, etc.

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge about "python limited method parameter type, return value type, variable type, etc." In the actual case operation process, many people will encounter such a dilemma, then let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

The role of the typing module

Since Python 3.5, PEP484 introduces type annotations for Python.

Type checking to prevent run-time parameter and return value types, variable types do not match.

As a development documentation add-on, it is convenient for the user to pass in and return parameter types when calling.

After the module is added, it will not affect the operation of the program, and will not report formal errors. Only remind pycharm that typing is currently supported. Parameter type errors will prompt yellow.

common types

int,long,float: int, long integer, float

bool,str: Boolean, string type

List, Tuple, Dictionary, Set: List, Tuple, Dictionary, Set

Iterable,Iterator: iterable type, iterator type

Generator: Generator type

basic type assignment

example

def test(a:int, b:str) -> str: print(a, b) return 1000if __name__ == '__main__': test('test', 'abc')

The function test, a:int specifies that the input parameter a is of type int, b:str b is of type str, and-> str returns a value of type srt.

As you can see, in the method, we end up returning an int, at which point pycharm will have a warning;

When we call this method, the parameter a we enter is a string, and there will also be warnings;

But a very important point is that pycharm only raises a warning, but in fact it does not report errors. After all, Python is still a dynamic language.

Complex Type Labeling

Examples 1

Have a problem and nobody answers? Xiaobian created a Python learning exchange QQ group: 579817333 looking for like-minded friends, mutual help, there are good video learning tutorials and PDF e-books in the group! '''from typing import ListVector = List[float]def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector]# typechecks; a list of floats qualifies as a Vector.new_vector = scale(2.0, [1.0, -4.2, 5.4])

Example 2

from typing import Dict, Tuple, SequenceConnectionOptions = Dict[str, str]Address = Tuple[str, int]Server = Tuple[Address, ConnectionOptions]def broadcast_message(message: str, servers: Sequence[Server]) -> None: ...# The static type checker will treat the previous type signature as# being exactly equivalent to this one.def broadcast_message( message: str, servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None: ...): ...

Note here that tuples are special because they are immutable.

So, when we specify Tuple[str, str], we can only pass in length 2 and all elements in the tuple are of type str

generic assignment

example

Have a problem and nobody answers? Xiaobian created a Python learning exchange QQ group: 579817333 looking for like-minded friends, mutual help, there are good video learning tutorials and PDF e-books in the group! '''from typing import Sequence, TypeVar, UnionT = TypeVar('T') # Declare type variabledef first(l: Sequence[T]) -> T: # Generic function return l[0]T = TypeVar('T') # Can be anythingA = TypeVar('A', str, bytes) # Must be str or bytesA = Union[str, None] # Must be str or None

Type assignment when creating variables

from typing import NamedTupleclass Employee(NamedTuple): name: str id: int = 3employee = Employee ('Guido ')assert employee.id == 3 Shortcomings

example

Have a problem and nobody answers? Xiaobian created a Python learning exchange QQ group: 579817333 looking for like-minded friends, mutual help, there are good video learning tutorials and PDF e-books in the group! '''from typing import Listdef test(b: List[int]) -> str: print(b) return 'test'if __name__ == '__main__': test([1, 'a'])

As you can see from this example, although we specify List[int] as a list of ints-in practice, as long as there is nt in this list (the others can be of any type), no warning will appear

"Python qualifies method parameter types, return value types, variable types, etc." The content is introduced here. Thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report