我通过在示例文件夹以外的另一个文件夹中进行测试来试验一些问题:
当从不同的文件夹创建时,数据集对象没有相同的类。
解释:在测试文件中,我创建了一个数据集对象,并启动了一个返回数据集对象的解析方法。所以我在 tests.py 中有 2 个数据集实例,它们的所有属性都是相等的。但是当我在 test.py 中创建一个“parseDataset”==“testDataset”时,我们到达了 Dataset 中的第一个 if。eq 函数,因为这两个对象不属于同一类: '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
测试.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- 好的,我测试了以下内容:
测试.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导入示例
。这很酷,它正在工作,但它很困惑。我必须更改项目中的所有相对路径。如果没有人有解决方案,我会这样做,因为我快没耐心了。
最佳答案
所以。经过多次尝试,this post给我解决方案。
$ tree
.
├── Makefile
├── sample
│ ├── parse.py
│ └── dataset.py
└── tests
└── tests.py
在我的 makefile 中,规则测试启动此命令:PYTHONPATH=。 python3.7 tests/tests.py -v
并且在 tests.py 中,我们有一个像这样的简单导入:import sample.dataset
“PYTHONPATH=.”方法是一个很好的解决方案,可以避免将项目打包到文件夹中并使用 python -m myproject.tests.tests
在该文件夹的根目录下启动。
关于python - 为什么在 Python 中从不同路径调用类时 __class__ 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61389362/