1

我有一系列模块,每个模块都包含一个我想通过组合混合到一个类中的行为。由于这些模块中的每一个都有一些通用和冗余代码,我试图提取一个基本模块,然后我可以将其导入每个模块,在删除样板文件的同时填写自定义代码。我的代码的简化版本如下:

主要.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)

基础.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)

具体的.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方式?

提前感谢=)

4

0 回答 0