简体   繁体   English

python函数的绝对导入

[英]python absolute import of the function

trend.py and test_trend.py are in the same folder. Trend.py和test_trend.py在同一文件夹中。 I have a class Trend with a function find_regres_values that is called from a instance method perform_analysis. 我有一个趋势类,该类具有从实例方法perform_analysis调用的功能find_regres_values。

trend.py: Trend.py:

class Trend:
    def __init__(self, values, trend_type):
        self.all_values = values

    def permorn_analysis(self, first, trend_type):
        #blabla
        vals_reg = ["a", "b", "c", "d"]
        find_regres_values(vals_reg, first, trend_type)

    def find_regres_values(vals_reg, first, trend_type):
        #do somethin
        pass

in test_trend.py 在test_trend.py中

from trend import find_regres_values
class ConsecRegions(unittest.TestCase):

    def test_find_regres_values_decreas_min_before_max(self):
        #initialize some values
        output = find_regres_values(vals_reg, first, trend_type)
        self.assertEqual(output, result)

It shows me an error: 它显示了一个错误:

  File "test_trend.py", line 2, in <module>
    from trend import find_regres_values
ImportError: cannot import name find_regres_values

How do I import one function for testing? 如何导入一个函数进行测试?

find_regres_values is a method of the class Trend , If you want find_regres_values to be its own function then remove the indentation find_regres_valuesTrend类的方法,如果您希望find_regres_values成为其自己的函数,则删除缩进

class Trend:
    def __init__(self, values, trend_type):
        self.all_values = values
    def permorn_analysis(self,first,trend_type)
        #blabla
        vals_reg = some list
        find_regres_values(vals_reg, first, trend_type)

def find_regres_values(vals_reg, first, trend_type):
    #do something

What Python version you use? 您使用什么Python版本?

If Python 3.x: 如果是Python 3.x:

Create empty file __init__.py 创建空文件__init__.py

For correct import use this code: 为了正确导入,请使用以下代码:

from trend import Trend

and edit call of method: 并编辑方法的调用:

from trend import Trend

class ConsecRegions(unittest.TestCase):

    def test_find_regres_values_decreas_min_before_max(self):
        #initialize some values
        output = Trend.find_regres_values(vals_reg, first, trend_type)
        self.assertEqual(output, result)

For information: 有关信息:

In file trend.py after permorn_analysis method insert a colon. 在permorn_analysis方法之后的文件Trend.py中,插入一个冒号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM