Python中是否有任何声明关键字? [英] Are there any declaration keywords in Python?

查看:30
本文介绍了Python中是否有任何声明关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 中是否有任何声明关键字,如 local、global、private、public 等.我知道它是无类型的,但你怎么知道这个语句:

Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:

x = 5;

  • 创建一个新变量.
    • 设置一个现有的.

    推荐答案

    我真的很喜欢 Van Gale 提供的理解,但它并没有真正回答你怎么知道这个陈述:创建一个新变量还是设置现有变量?"

    I really like the understanding that Van Gale is providing, but it doesn't really answer the question of, "how do you know if this statement: creates a new variable or sets an existing variable?"

    如果您想在查看代码时知道如何识别它,只需查找以前的作业即可.避免使用全局变量,不管怎样,这是一个很好的做法,你会一切就绪.

    If you want to know how to recognize it when looking at code, you simply look for a previous assignment. Avoid global variables, which is good practice anyway, and you'll be all set.

    以编程方式,您可以尝试引用该变量,然后查看是否出现名称错误"异常

    Programmatically, you could try to reference the variable, and see if you get a "Name Error" exception

    try:
        x
    except NameError:
        # x doesn't exist, do something
    else:
        # x exists, do something else
    

    我从来不需要这样做……而且我怀疑您是否真的需要这样做.

    I've never needed to do this... and I doubt you will really need to either.

    尽管对于习惯于一遍遍一遍又一遍地键入类名(或类型)的人来说,Python 看起来有点松散……它实际上与您想要的一样严格.

    Even though Python looks kinda loosey-goosey to someone who is used to having to type the class name (or type) over and over and over... it's actually exactly as strict as you want to make it.

    如果你想要严格类型,你可以明确地做:

    If you want strict types, you would do it explictly:

    assert(isinstance(variable, type))
    

    装饰器的存在以一种非常方便的方式调用函数...

    Decorators exist to do this in a very convenient way for function calls...

    不久之后,您可能会得出这样的结论:静态类型检查(在编译时)实际上并没有使您的代码变得更好.必须在所有地方都有冗余类型信息的成本只有很小的好处.

    Before long, you might just come to the conclusion that static type checking (at compile time) doesn't actually make your code that much better. There's only a small benefit for the cost of having to have redundant type information all over the place.

    我目前正在使用 actionscript,并输入以下内容:

    I'm currently working in actionscript, and typing things like:

    var win:ThingPicker = PopUpManager.createPopUp(fEmotionsButton, 
           ThingPicker, false) as ThingPicker;
    

    在python中看起来像:

    which in python would look like:

    win = createPopup(parent, ThingPicker)
    

    我可以看到,查看 actionscript 代码,静态类型检查根本没有任何好处.变量的生命周期太短了,以至于我必须完全喝醉才能用它做错误的事情……并让编译器通过指出类型错误来拯救我.

    And I can see, looking at the actionscript code, that there's simply no benefit to the static type-checking. The variable's lifetime is so short that I would have to be completely drunk to do the wrong thing with it... and have the compiler save me by pointing out a type error.

    这篇关于Python中是否有任何声明关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆