Are there any declaration keywords in Python?

前端 未结 5 1979
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 10:48

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;
         


        
5条回答
  •  佛祖请我去吃肉
    2021-02-03 11:14

    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.

    soapbox alert !!!

    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.

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

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

    which in python would look like:

    win = createPopup(parent, ThingPicker)
    

    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.

提交回复
热议问题