Python抽象调用基类中导入的库的正确方法

标签 python python-3.x abstract-class abc

使用抽象类的基类中导入的函数的正确方法是什么?例如:在 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/

相关文章:

python - 如何将 Excel 文件从付费专区下载到 pandas 数据框中?

python - 检查行值 value 是否等于列名并访问该列的值

Python 3 字节格式

java - 有一个带注释的抽象 Controller 类是否有意义 - Spring MVC

c# - 使用 CaSTLe Windsor 进行抽象类依赖注入(inject)

python - 如何使用发布数据重定向(Django)

Python 为 S3 Post 生成的签名

c# - 类实现抽象类的通用类型约束

Python3.6 - 无法导入名称 '_imaging' [Django 2.1.2、Apache 2、CentOS 7]

python-3.x - 将 Scapy L3socket 与 WSL 结合使用时,协议(protocol)不支持地址族