简体   繁体   English

在python中用格式变量声明变量的目的是什么:class type =?

[英]What is the purpose of declaring a variable with the format variable : class type = in python?

I am new to programming in general.我是编程新手。 I would like to know why this symbol is being used in a few codes.我想知道为什么在一些代码中使用这个符号。 What I mean is, what is the purpose of this way of declaring a variable?我的意思是,这种声明变量的方式的目的是什么? Is it useful?有用吗?

For example let's say I define例如,假设我定义

say_hello1 = "hello everybody"

I could also define the same variable using:我还可以使用以下方法定义相同的变量:

say_hello2 : str = "hello everybody"

Or ..或者 ..

say_hello3 : float = "hello everybody" # I know this is not a float variable, I'm doing it on purpose

Each variable (say_hello1, say_hello2 and say_hello3 ) will be the same type (string).每个变量(say_hello1、say_hello2 和 say_hello3)都是相同的类型(字符串)。 So what is the purpose of this way of declaring variables?那么这种声明变量的方式的目的是什么? Is it just to say that the variable will be a specific type?只是说变量将是特定类型吗? Or does it change anything else (ie the efficency of the code)?或者它是否改变了其他任何东西(即代码的效率)?

Thanks in advance.提前致谢。

It shows what variable you are expecting, which makes your code a lot easier to read and understand.它显示了您期望的变量,这使您的代码更易于阅读和理解。 It can also help with linters and other third party tools.它还可以帮助使用 linter 和其他第三方工具。 Python itself won't look at it afaik. Python本身不会看它afaik。

Take a look here: https://docs.python.org/3/library/typing.html看看这里: https : //docs.python.org/3/library/typing.html

Python is not a strongly-typed language. Python 不是强类型语言。 The variable : type is just for readability, does not declare strongly typed variables. variable : type只是为了可读性,不声明强类型变量。 Later you can change the value, even in another type.稍后您可以更改该值,即使是另一种类型。

Type hints were introduced in PEP-484 . PEP-484中引入了类型提示。 The goal is to allow additional tools to do static linting based on the acceptable types for a variables.目标是允许其他工具根据变量的可接受类型进行静态 linting。 This is included for example in PyCharm, and is used by mypy .例如,这包含在 PyCharm 中,并由mypy 使用

But anyway, Python is a dynamic language, and the interpretor just ignores those declared type hints.但无论如何,Python 是一种动态语言,解释器只会忽略那些声明的类型提示。

In this case the type is pretty obvious so it is not very helpful but assume that you have a base class BaseClass that some other classes inherit SubClassA and SubClassB , then:在这种情况下,类型非常明显,所以它不是很有帮助,但假设您有一个基类BaseClass其他一些类继承SubClassASubClassB ,然后:

a: SubClassA = SubClassA()  # not very useful
a: BaseClass = SubClassA()  # indicates that you expect a given interface, no necessarily SubClassA

### another dev can safely replace code later on
a: BaseClassA = SubClassB()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM