使用抽象类的基类中导入的函数的正确方法是什么?例如:在 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
导入的库?
最佳答案
抽象方法本身不关心实现细节。
如果您需要特定的模块来实现特定的具体实现,则需要将其导入到您的模块中:
import base
import functions
class DietPizza(base.BasePizza):
@staticmethod
def get_ingredients():
return functions.istrue()
请注意,在多个位置导入模块不会花费任何额外费用。当一个模块在多个其他模块中使用时,Python 会重新使用已创建的模块对象。
关于Python抽象调用基类中导入的库的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30513903/