Python: How can I import all variables?

前端 未结 4 1059
广开言路
广开言路 2020-12-09 07:42

I\'m new to Python and programming in general (a couple of weeks at most).

Concerning Python and using modules, I realise that functions can imported using fro

4条回答
  •  我在风中等你
    2020-12-09 08:03

    Just for some context, most linters will flag from module import * with a warning, because it's prone to namespace collisions that will cause headaches down the road.

    Nobody has noted yet that, as an alternative, you can use the

    from a import name, age
    

    form and then use name and age directly (without the a. prefix). The from [module] import [identifiers] form is more future proof because you can easily see when one import will be overriding another.

    Also note that "variables" aren't different from functions in Python in terms of how they're addressed -- every identifier like name or sayBye is pointing at some kind of object. The identifier name is pointing at a string object, sayBye is pointing at a function object, and age is pointing at an integer object. When you tell Python:

    from a import name, age
    

    you're saying "take those objects pointed at by name and age within module a and point at them in the current scope with the same identifiers".

    Similarly, if you want to point at them with different identifiers on import, you can use the

    from a import sayBye as bidFarewell
    

    form. The same function object gets pointed at, except in the current scope the identifier pointing at it is bidFarewell whereas in module a the identifier pointing at it is sayBye.

提交回复
热议问题