简体   繁体   中英

How to call a procedure inside of another procedure

I'm working on creating a large .py file that can be imported and used to solve mathematical formulas. I'd like to store the formulas in a procedure that is called input1_input2_input3(): for example the formual distance=speed*time is called dis_spe_tim().

The code so far is:

def dis_spe_tim():
    def distance(speed, time):
        result = speed*time
        unit = input("What unit are you measuring the distance in?")
        print(resule,unit)

    def speed():
        print("speed")

and I would ideally like the user to use this like so:

import equations #name of the .py file
from equations import *
dis_spe_tim.distance(1,2)

Unfortunately, this is my first time ever doing something like this so I have absolutely no idea how to go about calling the procedure inside of the procedure and providing its arguments.

Short answer: you can't. Nested functions are local to the function they're defined in and only exists during the outer function's execution ( def is an executable statement that, at runtime, creates a function object and bind it to it's name in the enclosing namespace).

The canonical python solution is to use modules as namespaces (well, Python modules ARE, mainly, namespaces), ie have a distinct module for each "formula", and define the functions at the module's top-level:

# dis_spe_tim.py
def distance(speed, time):
   # code here

def speed():
   # code here

Then put all those modules in an equations package (mostly: a folder containing modules and an __init__.py file). Then you can do:

from equations import dis_spe_tim
dis_spe_tim.distance(1,2)

You can check the doc for more on modules and packages here: https://docs.python.org/3/tutorial/modules.html#packages

Also note that

1/ "star imports" (also named "wildcard imports"), ie from somemodule import * , are highly discouraged as they tend to make the code harder to read and maintain and can cause unexpected (and sometimes subtles enough to be hard to spot) breakages.

2/ you shouldn't mix "domain" code (code that do effective computations) with UI code (code that communicates with the user), so any call to input() , print() etc should be outside the "domain" code. This is key to make your domain code usable with different UIs (command-line, text-based (curse etc), GUI, web, whatever), but also, quite simply, to make sure your domain code is easily testable in isolation (unit testing...).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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