我的问题是当两个模块中有两个相同的命名函数时,计算机如何选择运行函数。其中一个模块已导入。
这是Pythonschool的一个例子。
我有一个名为crops.py的文件:
from wheat_class import *
from potato_class import *
#test program to select a crop and manage the crop
def display_menu():
print()
print("Which crop would you like to create?")
print()
print("1. Potato")
print("2. Wheat")
print()
print("Please select an option from the above menu")
def select_option():
valid_option = False
while not valid_option:
try:
choice = int(input("Option selected: "))
if choice in (1,2):
valid_option = True
else:
print("Please enter a valid option")
except ValueError:
print("Please enter a valid option")
return choice
def create_crop():
display_menu()
choice = select_option()
if choice == 1:
new_crop = Potato()
elif choice == 2:
new_crop = Wheat()
return new_crop
def main():
new_crop = create_crop()
manage_crop(new_crop)
if __name__ == "__main__":
main()
wheat_class和potato_class是名为Crop的类的子类。 Crop类在crop_class.py中定义:
class Crop:
"""A generic food crop"""
#constructor = runs automatically when instantiating
def __init__(self,growth_rate,light_need,water_need):
#set the attributes
#if underscore in front of name, private attributes
self._growth = 0
self._days_growing = 0
self._growth_rate = growth_rate
self._light_need = light_need
self._water_need = water_need
self._status = "Seed"
self._type = "Generic"
def needs(self):
some code
def report(self):
some code
def _update_status(self):
#code for updating status of crop
def grow(self,light,water):
#code increasing growth value
def auto_grow(crop,days):
some code
def manual_grow(crop):
some code
def display_menu():
print("1. Grow manually over 1 day")
print("2. Grow automatically over 30 days")
print("3. Report status")
print("0. Exit test program")
print()
print("Please select an option from the above menu")
def get_menu_choice():
option_valid = False
while not option_valid:
try:
choice = int(input("Option Selected: "))
if 0 <= choice <= 3:
option_valid = Tsame furue
else:
print("Value entered not valid - please enter a value between 0 and 3")
except ValueError:
print("Value entered not valid - please enter a value between 0 and 3")
return choice
def manage_crop(crop):
print("This is the crop management program")
print()
noexit = True
while noexit:
display_menu()
option = get_menu_choice()
if option == 1:
manual_grow(crop)
elif option == 2:
auto_grow(crop,30)
elif option == 3:
print(crop.report())
print()
elif option == 0:
noexit = False
print()
我的问题是关于函数display_menu()。
如图所示,该函数存在于crops.py和crop_class.py中。
运行crops.py中的main函数时,将运行crops.py中的display_menu()
new_crop = create_crop()
同时运行crop_class.py中的display_menu()
manage_crop(new_crop)
。
我很困惑,因为这两个函数都没有归因于特定的类。 crop_class.py中的display_menu()以某种方式缩进,使其不属于Crop类。 因此,我对计算机如何选择运行代码感到困惑。对此规则的破坏将非常有帮助。