如何在python中声明变量类型,C风格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3933197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to declare variable type, C style in python
提问by Guillermo Siliceo Trueba
i'm a programming student and my teacher is starting with C to teach us the programming paradigms, he said it's ok if i deliver my homework in python(it's easier and faster for the homeworks). And i would like to have my code to be as close as posible as in plain C. Question is How do i declare data types for variables in python like you do in C. ex:
我是一名编程专业的学生,我的老师从 C 开始教我们编程范式,他说如果我用 python 交作业就可以了(作业更容易更快)。而且我希望我的代码尽可能接近纯 C。问题是我如何像在 C 中那样在 python 中声明变量的数据类型。例如:
int X,Y,Z;
I know i can do this in python
我知道我可以在 python 中做到这一点
x = 0
y = 0
z = 0
But that seems a lot of work and it misses the point of python being easier/faster than C. So, whats the shorttest wayto do this? P.S. i know you dont have todeclare the data type in python most of the time, but still i would like to do it so my code looks as much possible like classmates'.
但这似乎有很多工作,而且它忽略了 python 比 C 更容易/更快的点。那么,最快捷的方法是什么?PS 我知道大多数时候你不必在 python 中声明数据类型,但我仍然想这样做,所以我的代码看起来尽可能像同学的。
采纳答案by Ignacio Vazquez-Abrams
There is no way to declare variables in Python, since neither "declaration" nor "variables" in the C sense exist. This will bindthe three namesto the same object:
没有办法在 Python 中声明变量,因为 C 意义上的“声明”和“变量”都不存在。这会将三个名称绑定到同一个对象:
x = y = z = 0
回答by KevinDTimm
Python isn't necessarily easier/faster than C, though it's possiblethat it's simpler ;)
Python 不一定比 C 更容易/更快,尽管它可能更简单;)
To clarify another statement you made, "you don't have to declare the data type" - it should be restated that you can'tdeclare the data type. When you assign a value to a variable, the type of the value becomes the type of the variable. It's a subtle difference, but different nonetheless.
为了澄清您所做的另一项声明,“您不必声明数据类型” - 应该重申您不能声明数据类型。当您为变量赋值时,值的类型成为变量的类型。这是一个微妙的区别,但仍然不同。
回答by martineau
Everything in Python is an object, and that includes classes, class instances, code in functions, libraries of functions called modules, as well as data values like integers, floating-point numbers, strings, or containers like lists and dictionaries. It even includes namespaces which are dictionary-like (or mapping) containers which are used to keep track of the associations between identifier names (character string objects) and to the objects which currently exist. An object can even have multiple names if two or more identifiers become associated with the same object.
Python 中的一切都是对象,包括类、类实例、函数中的代码、称为模块的函数库,以及整数、浮点数、字符串等数据值或列表和字典等容器。它甚至包括名称空间,它们是类似字典(或映射)的容器,用于跟踪标识符名称(字符串对象)与当前存在的对象之间的关联。如果两个或多个标识符与同一个对象相关联,则对象甚至可以有多个名称。
Associating an identifier with an object is called "binding a name to the object". That's the closest thing to a variable declaration there is in Python. Names can be associated with different objects at different times, so it makes no sense to declare what type of data you're going to attach one to -- you just do it. Often it's done in one line or block of code which specifies both the name and a definition of the object's value causing it to be created, like <variable> = 0or a function starting with a def <funcname>.
将标识符与对象相关联称为“将名称绑定到对象”。这是 Python 中最接近变量声明的东西。名称可以在不同的时间与不同的对象相关联,因此声明您将要附加的数据类型是没有意义的——您只需这样做。通常它是在一行或一行代码中完成的,它指定了对象的名称和值的定义,导致它被创建,例如<variable> = 0或以def <funcname>.
How this helps.
这有什么帮助。
回答by Carl Pickering
But strong types and variable definitions are actually there to make development easier. If you haven't thought these things through in advance you're not designing and developing code but merely hacking.
但是强类型和变量定义实际上是为了使开发更容易。如果您事先没有考虑过这些事情,那么您就不是在设计和开发代码,而只是在进行黑客攻击。
Loose types simply shift the complexity from "design/hack" time to run time.
松散类型只是将复杂性从“设计/黑客”时间转移到运行时间。
回答by DisplayName
I'm surprised no one has pointed out that you actually can do this:
我很惊讶没有人指出你实际上可以做到这一点:
decimalTwenty = float(20)
In a lot of cases it is meaningless to type a variable, as it can be retyped at any time. However in the above example it could be useful. There are other type functions like this such as: int(), long(), float()and complex()
在很多情况下,输入变量是没有意义的,因为它可以随时重新输入。但是在上面的例子中它可能很有用。还有其他类型的功能是这样,例如:int(),long(),float()和complex()
回答by Cam T
Starting with Python 3.6, you can declare types of variables and funtions, like this :
从 Python 3.6 开始,您可以声明变量和函数的类型,如下所示:
explicit_number: type
or for a function
或者对于一个函数
def function(explicit_number: type) -> type:
pass
This example from this post: How to Use Static Type Checking in Python 3.6is more explicit
这篇文章中的这个例子:How to Use Static Type Checking in Python 3.6更明确
from typing import Dict
def get_first_name(full_name: str) -> str:
return full_name.split(" ")[0]
fallback_name: Dict[str, str] = {
"first_name": "UserFirstName",
"last_name": "UserLastName"
}
raw_name: str = input("Please enter your name: ")
first_name: str = get_first_name(raw_name)
# If the user didn't type anything in, use the fallback name
if not first_name:
first_name = get_first_name(fallback_name)
print(f"Hi, {first_name}!")
See the docs for the typingmodule
回答by Praphan Klairith
Simply said: Typing in python is useful for hinting only.
简单地说:在 python 中键入仅用于提示。
x: int
y: int
z: int

