我在初始化 class 时收到警告,在 Python 中显示 'parameter value is not used'

I get a warning when initializing a class that says 'parameter value is not used' in Python

我有以下代码,其中一个 class 具有 3 个属性和两个函数。

import json


class Song:
    def __init__(self, name, artist, full_title=None):
        self.name = name
        self.artist = artist
        self.full_title = self.name + ' ' + self.artist


def save_json(list_of_objects, json_file):
    # json save
    with open(json_file, 'w') as fp:
        json.dump(list_of_objects, fp, indent=4)


def load_json(json_file):
    # json load
    with open(json_file, 'r') as fp:
        loaded_data = json.load(fp)
    return loaded_data


file = 'my_songs.json'

song1 = Song('Roar', 'Katy Perry')
song2 = Song('Hello', 'Adele')
song3 = Song('Grenade', 'Bruno Mars')


list_of_songs = [song1, song2, song3]
list_of_songs_dict = [vars(s) for s in list_of_songs]

save_json(list_of_songs_dict, file)

如您所见,该对象使用三个参数(名称、艺术家、full_title)初始化

代码创建对象列表并将其转储到名为 'my_songs.json'.

的 json 文件中

json 文件如下所示

[
    {
        "name": "Roar",
        "artist": "Katy Perry",
        "full_title": "Roar Katy Perry"
    },
    {
        "name": "Hello",
        "artist": "Adele",
        "full_title": "Hello Adele"
    },
    {
        "name": "Grenade",
        "artist": "Bruno Mars",
        "full_title": "Grenade Bruno Mars"
    }
]

我想从 json 文件(名为 'my_songs.json')重新创建名为 'list_of_songs' 的列表。

我是这样做的:

loaded_songs = load_json(file)

list_of_songs_from_json = [Song(**o) for o in loaded_songs]
print(list_of_songs_from_json)

IDE 显示了一个警告 'parameter full_title value is not used'

如果我从 class 初始化中删除 'full_title=None',我会收到以下错误消息:

TypeError: __init__() got an unexpected keyword argument 'full_title'

'full_title=None'在class初始化中的原因是在某些情况下,我想使用2个参数定义对象,而在其他情况下(比如从json 文件)我想使用 3 个参数定义对象。

我怀疑有 'correct' 或 'better' 方法可以做到这一点,因此出现警告。关于如何删除警告并实现代码已经执行的操作,有什么建议吗?

谢谢。

full_title不是None时,您需要添加信息。警告来了,因为 对于 self.full_title,您使用的是 self.aself.b,如果 full_title 不是 None,则每次都不会使用它的值。

所以对您的代码进行一些修改,检查 full_title 是否为 None

class Song:
def __init__(self, name, artist, full_title=None):
    self.name = name
    self.artist = artist
    if full_title is None:
         self.full_title = self.name + ' ' + self.artist
    else:
         self.full_title = full_title