Note that there are some explanatory texts on larger screens.

plurals
  1. POExtending module functionality in python
    primarykey
    data
    text
    <p>I have a series of modules, each of which contains a behavior which I want to mix into a class via composition. Since each of these modules has some common &amp; redundant code, I attempted to extract out a base module which I could then import into each module, filling in the custom code while cutting out the boilerplate. A simplified version of my code is below:</p> <p>main.py:</p> <pre><code>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) </code></pre> <p>base.py:</p> <pre><code># 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) </code></pre> <p>concrete.py:</p> <pre><code>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" </code></pre> <p>When I run main.py, I get an exception:</p> <pre><code>Traceback (most recent call last): File "main.py", line 14, in &lt;module&gt; 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 </code></pre> <p>My question is this: Is there a way to extend the functionality of a module, or inversely to extract common functionality out of multiple modules into a base module, without lots of extra lines of code? What is the pythonic way?</p> <p>Thanks in advance =)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload