【问题标题】:Python Abstract Proper Way of Calling Library Imported in Base ClassPython抽象调用基类中导入库的正确方法
【发布时间】:2015-05-28 18:01:16
【问题描述】:

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

【问题讨论】:

  • 再次导入模块或委托给方法有什么问题?
  • ...你说from base import functions
  • 我认为 import base.py 也不是有效的 python .... 除非你的文件布局真的很不稳定

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


【解决方案1】:

抽象方法不关心实现细节

如果您需要特定模块用于特定的具体实现,则需要将其导入模块中:

import base
import functions


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

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

【讨论】:

  • 好的,谢谢。我只是想确定正确的程序。不好学不正确的方法。
猜你喜欢
  • 1970-01-01
  • 2018-07-16
  • 2015-06-14
  • 2019-08-31
  • 2012-09-21
  • 2016-07-05
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
相关资源
最近更新 更多