简体   繁体   English

如何在python中声明变量类型,C风格

[英]how to declare variable type, C style in python

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).我是一名编程专业的学生,​​我的老师从 C 开始教我们编程范式,他说如果我用 python 交作业就可以了(作业更容易更快)。 And I would like to have my code to be as close as possible as in plain C.我希望我的代码尽可能接近纯 C。
Question is:问题是:
How do I declare data types for variables in python like you do in C. ex:我如何像在 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 shortest way to do this?但这似乎需要做很多工作,而且它忽略了 Python 比 C 更容易/更快的重点。那么,这样的最短方法是什么?
PS I know you don't have to declare 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'. PS我知道你没有在Python的大部分时间申报的数据类型,但我仍想做到这一点,所以我的代码看起来尽可能多尽可能像同学们。

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.6 is 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 typing module请参阅typing模块文档

Edit: Python 3.5 introduced type hints which introduced a way to specify the type of a variable.编辑:Python 3.5 引入了类型提示,它引入了一种指定变量类型的方法。 This answer was written before this feature became available.此答案是在此功能可用之前编写的。

There is no way to declare variables in Python, since neither "declaration" nor "variables" in the C sense exist.没有办法在 Python 中声明变量,因为 C 意义上的“声明”和“变量”都不存在。 This will bind the three names to the same object:这会将三个名称绑定到同一个对象:

x = y = z = 0

Python isn't necessarily easier/faster than C, though it's possible that 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't declare 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.这是一个微妙的区别,但仍然不同。

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()

Simply said: Typing in python is useful for hinting only.简单地说:在 python 中键入仅用于提示。

x: int = 0
y: int = 0 
z: int = 0

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.松散类型只是将复杂性从“设计/黑客”时间转移到运行时间。

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. Python 中的一切都是对象,包括类、类实例、函数中的代码、称为模块的函数库,以及整数、浮点数、字符串等数据值或列表和字典等容器。 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.如果两个或多个标识符与同一个对象相关联,则对象甚至可以有多个名称。

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.这是 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> = 0 or a function starting with a def <funcname> .通常它是在一行或一行代码中完成的,它指定了对象的名称和值的定义,导致它被创建,例如<variable> = 0或以def <funcname>开头的函数。

How this helps.这有什么帮助。

I use data types to assert unique values in python 2 and 3. Otherwise I cant make them work like a str or int types.我使用数据类型来断言 python 2 和 3 中的唯一值。否则我不能让它们像 str 或 int 类型一样工作。 However if you need to check a value that can have any type except a specific one, then they are mighty useful and make code read better.但是,如果您需要检查可以具有特定类型之外的任何类型的值,那么它们非常有用并且可以使代码更好地阅读。

Example : you might want to conditionally filter or print a value using a condition or a function handler.示例:您可能希望使用条件或函数处理程序有条件地过滤或打印值。

from __future__ import print_function # for python2 & 3 to work
class unset(object):
    pass


def some_func(a,b, show_if=unset):
    result = a + b
    
    ## just return it
    if show_if is unset:
        return result
    
    ## handle show_if to conditionally output something
    if hasattr(show_if,'__call__'):
        if show_if(result):
            print("show_if("+ str(result) +")", result)
    elif show_if:
        print(show_if, " condition met ", result)
        
    return result
    
print("Are > 5)")
for i in range(10):
    result = some_func(i,2, show_if= i>5 )
    
def is_even(val):
    return not val % 2

print("Are even")
for i in range(10):
    result = some_func(i,2, show_if= is_even )

Output输出

Are > 5)
True  condition met  8
True  condition met  9
True  condition met  10
True  condition met  11
Are even
show_if(2) 2
show_if(4) 4
show_if(6) 6
show_if(8) 8
show_if(10) 10

if show_if=unset is perfect use case for this because its safer and reads well. if show_if=unset是完美的用例,因为它更安全且show_if=unset好。 I have also used them in enums which are not really a thing in python.我也在枚举中使用了它们,这在 python 中并不是真正的东西。

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

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