我有一系列模块,每个模块都包含一个我希望通过合成混合到一个类中的行为。由于这些模块中的每一个都有一些共同的和冗余代码,我试图提取一个基本模块,然后我可以将其导入每个模块,填写自定义代码,同时切断样板。我的代码的简化版本如下:
main.py:
import concrete as steak_sauce
class Customer():
def __init__(self):
self.allergies = ["onions"]
self.dish = []
def register_ingredient (steak_sauce):
self.dish.append(ingredient)
customer = Customer()
customer.eat_if_not_allergic(steak_sauce)
base.py:
# Base module
menu_item_name = "default"
menu_item_ingredients = []
def is_allergic(customer):
if menu_item_name in customer.allergies:
return True
else:
add_to_dish(menu_item_name)
def eat_if_not_allergic(customer):
if not is_allergic(customer):
eat_it(ingredient)
concrete.py:
from base import *
menu_item_name = "steak sauce"
menu_item_ingredients = ["MSG", "Blood"]
def eat_it(customer):
print "custom logic acting on customer goes here"
当我运行main.py时,我得到一个例外:
Traceback (most recent call last):
File "main.py", line 14, in <module>
customer.add_if_not_allergic(steak_sauce)
File "main.py", line 10, in add_if_not_allergic
if not ingredient.is_allergic(customer):
File "/home/chazu/tests/base.py", line 10, in is_allergic
add_to_dish(menu_item_name)
NameError: global name 'eat_it' is not defined
我的问题是:有没有办法扩展模块的功能,或者反过来将多个模块中的常用功能提取到基本模块中,而不需要额外的代码行?什么是pythonic方式?
提前致谢=)