如何在其他类中使用Python数据类

cetgtptt  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(127)

我试图掌握Python,但在尝试使用Dataclasses时似乎遇到了障碍。但当我运行测试时,我得到了Assert错误,因为它似乎没有正确地看到数据类。
下面的代码:
文件:音乐库.py

from dataclasses import dataclass

@dataclass
class Track:
    title: str
    artist: str
    file: str

class MusicLibrary:
    def __init__(self):
        self.track = Track

    def all(self):
        return self.track

    def add(self, title, artist, file):
        self.track(title = title, artist = artist, file = file)

add函数从测试中被调用,并被传递三个参数:

import unittest

from player.music_library import MusicLibrary

class TestMusicLibrary(unittest.TestCase):

    ml = MusicLibrary()

    def test_all(self):
        ml = MusicLibrary()
        ml.add("Track1", "artist1","file1")
        self.assertEqual(ml.all(), ["Track1","artist1","file1" ])

然而,测试失败,

Traceback (most recent call last):
  File "/projects/python/python-music-player-challenges/seed/tests/test_music_library.py", line 13, in test_all
    self.assertEqual(ml.all(), ["Track1","artist1","file1" ])
AssertionError: <class 'player.music_library.Track'> != ['Track1', 'artist1', 'file1']

这是怎么回事?我显然错过了一些明显的东西。
谢谢

rqcrx0a6

rqcrx0a61#

更新music_library.py,如下所示:

from dataclasses import dataclass

@dataclass
class Track:
    title: str
    artist: str
    file: str

class MusicLibrary:
    def __init__(self):
        self.track = None

    def all(self):
        return self.track

    def add(self, title, artist, file):
        self.track = Track(title=title, artist=artist, file=file)

注意上面代码中的Dataclass示例化。
并像这样更新您的测试用例:

import unittest

from music_library import MusicLibrary

class TestMusicLibrary(unittest.TestCase):

    def test_all(self):
        ml = MusicLibrary()
        ml.add("Track1", "artist1", "file1")
        self.assertEqual([ml.all().title, ml.all().artist, ml.all().file],
                         ["Track1", "artist1", "file1"])

在您的测试代码中,您要比较不同的对象类型,您应该首先将ml.all()的输出转换为list。
如果运行测试,则会得到以下输出:

Ran 1 test in 0.000s

OK

相关问题