【问题标题】:why __class__ are different when calling a class from different paths in Python?为什么在 Python 中从不同路径调用类时 __class__ 会有所不同?
【发布时间】: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。这很酷,它正在工作,但它很混乱。我必须更改项目中的所有相对路径。如果没有人有解决方案,我会这样做,因为我已经没有耐心了。

【问题讨论】:

  • datasetsample.dataset 不是同一个模块,它们只是共享相同的源代码。如果您不想重复模块,请不要修改 sys.path。为什么要修改sys.path
  • 这是包含我的模块的许多测试和搜索的结果。因为我的结构与您的示例不同。我从 ./tests 开始,而不是从 ./ 那么如何从测试模块正确导入我的示例模块?
  • 如何在 ./tests 中启动 python,我可以导入模块 ../sample/dataset.py 吗?

标签: python python-3.x class types


【解决方案1】:

所以。经过多次尝试,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 在其根目录下启动的一个很好的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多