【发布时间】:2020-08-06 21:42:34
【问题描述】:
我在示例文件夹之外的另一个文件夹中进行测试时遇到了一些问题:
从不同文件夹创建时,数据集对象没有相同的类。
说明:在测试文件中,我创建了一个数据集对象,并启动了一个解析方法,该方法也返回一个数据集对象。所以我在tests.py中有2个数据集实例,它们的所有属性都是相等的。但是当我在 test.py 中创建一个“parseDataset”==“testDataset”时,我们会到达 Dataset.eq 函数中的第一个 if,因为这两个对象不属于同一类: 'sample.dataset.Dataset' 和 'dataset.Dataset'
树:
jojomoon at MacBook-Pro-de-Johann in /tmp/test
$ tree .
.
├── sample
│ ├── dataset.py
│ └── parse.py
└── tests
└── tests.py
2 directories, 3 files
数据集.py
import sys
import strings
class Dataset(object):
def __init__(self, dataTab):
self.nbFeat = len(dataTab[0])
self.nbData = len(dataTab)
# ... other cool stuff but doesn't care here
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.__dict__ == other.__dict__
解析.py
def dataset(fileName):
#... parse the file, and create an array
return dataset.Dataset(array)
# the array is the same as the one in tests.py
tests.py
import unittest
import os
# Get current path
current = os.path.dirname(os.path.abspath(__file__))
# Get parent path
parent = os.path.dirname(current)
# Add parent to python paths
sys.path.append(parent)
# Add sample to python paths
sys.path.append(parent + "/sample")
from sample import parse, dataset
class TestStringMethods(unittest.TestCase):
def test_parse_Unit_normal(self):
# ... opening a file, writing to it an example dataset.
# now launching a parse on it:
outputDS = parse.dataSet("./data/test_parse_Unit_normal.csv")
# create the expected dataset
expectTab = [
["Data1","Data2","Data3","Data4"],
["1","2","3","4"],
["5","6","7","8"]
]
expectDS = dataset.Dataset(expectTab)
# here outputDS.__class__ = <class 'sample.dataset.Dataset'>
# and expextDS.__class__ = <class 'dataset.Dataset'>
# so in the Dataset.__eq__() function, isinstance(other.__class__, self.__class__) = False
self.assertTrue(outputDS == expectDS)
我该如何解决这个问题?是的,我可以在 tests.py 中逐值比较或删除数据集类中的实例条件,但这只是在避免问题,而不是解决问题。
-EDIT- 我知道问题在于我在tests.py 中的导入。如何在 tests.py 中导入我的示例模块?相对路径:../sample
-EDIT2- 好的,我测试了以下内容:
tests.py
from ..sample import dataset
并得到这个错误:
Traceback (most recent call last):
File "tests/tests.py", line 20, in <module>
from ..sample import dataset
ValueError: attempted relative import beyond top-level package
所以通过搜索我找到了解释,但没有其他解决方案可以让我的类型问题消失
-EDIT3- 所以当(在我的示例中)我转到名为 dslr 的项目的父目录并使用 python3.7 -m dslr.tests.tests 启动时,以下行有效:from dslr import sample。这很酷,它正在工作,但它很混乱。我必须更改项目中的所有相对路径。如果没有人有解决方案,我会这样做,因为我已经没有耐心了。
【问题讨论】:
-
dataset和sample.dataset不是同一个模块,它们只是共享相同的源代码。如果您不想重复模块,请不要修改sys.path。为什么要修改sys.path? -
这是包含我的模块的许多测试和搜索的结果。因为我的结构与您的示例不同。我从 ./tests 开始,而不是从 ./ 那么如何从测试模块正确导入我的示例模块?
-
如何在 ./tests 中启动 python,我可以导入模块 ../sample/dataset.py 吗?
标签: python python-3.x class types