2

使用在抽象类的基类中导入的函数的正确方法是什么?例如:在base.py我有以下内容:

import abc
import functions 

class BasePizza(object):
    __metaclass__  = abc.ABCMeta

    @abc.abstractmethod
    def get_ingredients(self):
         """Returns the ingredient list."""

然后我在中定义方法diet.py

import base

class DietPizza(base.BasePizza):
    @staticmethod
    def get_ingredients():
        if functions.istrue():
            return True
        else:
            retrun False

但是,如果我尝试运行

python diet.py

我得到以下信息:

NameError: name 'functions' is not defined

如何diet.py识别由 导入的库base.py

4

1 回答 1

4

抽象方法不关心实现细节

如果你需要一个特定的模块来实现你的具体实现,你需要在你的模块中导入这个:

import base
import functions


class DietPizza(base.BasePizza):
    @staticmethod
    def get_ingredients():
        return functions.istrue()

请注意,在多个地方导入模块不会花费任何额外费用。当一个模块在多个其他模块中使用时,Python 会重用已经创建的模块对象。

于 2015-05-28T18:04:18.083 回答