How can I import multiple items from a module and rename them in Python?

后端 未结 2 1444
粉色の甜心
粉色の甜心 2021-01-04 04:50

I want to import atan and degree from math and rename them both.

I have tried using this:

from math import ata         


        
相关标签:
2条回答
  • 2021-01-04 05:18

    The Python Reference Manual does, in fact, cover this. It says, in its description for the import statement:

    import_stmt     ::=  "import" module ["as" name] ( "," module ["as" name] )*
                         | "from" relative_module "import" identifier ["as" name]
                         ( "," identifier ["as" name] )*
                         | "from" relative_module "import" "(" identifier ["as" name]
                         ( "," identifier ["as" name] )* [","] ")"
                         | "from" module "import" "*"
    

    Now, this notation is a little confusing at first glance, but as spend time with programming languages you will become more familiar with it. It is commonly refered to as "BNF" (which stands for Backus-Naur Form). Most programming language references will use some version of it.

    From the sample above, we see the following symbols that could do with some explanation:

    • Vertical bar or Pipe character ( | ) -- this is used to separate alternatives
    • The asterisk / star character ( * ) -- this means that the preceding (usually enclosed statement) is repeated zero or more times
    • Square brackets ([ and ]) -- these indicate that the enclosed portion which occurs is optional, so included zero or one times.
    • Parenthesis (( and )) -- these are used to group statements for the asterisk to take affect on

    Cutting down the reference above to what you seem interested in, we have:

    "from" relative_module "import" identifier ["as" name]
                         ( "," identifier ["as" name] )*
    

    TL;DR Which, for your example given, leads to the legal statement being

    from math import atan as t, degree as z
    
    0 讨论(0)
  • 2021-01-04 05:19

    You have to use the as for each item:

    from math import atan as t, degree as z
    

    This imports and renames them all.

    0 讨论(0)
提交回复
热议问题