[英]Have the class as value in a dictionary
我有一堂課:
class Competition:
def __init__(self, year = int, distance = int, stages = int, winner = None , cyclist = list):
self.year = year
self.distance = distance
self.stages = stages
self.winner = winner
self.cyclist = cyclist
def __str__(self):
return "Competition({}, {}, {}, {}, {}".format(self.year, self.distance, self.stages, self.winner, self.cyclist)
def __repr__(self):
return "{} {} {} {} {}".format(self.year, self.distance, self.stages, self.winner, self.cyclist)
我想將該類添加到字典中作為值,並作為年份的關鍵。 我得到的信息來自一個文件。
所以我有這個
with open('tour-de-france.csv') as file:
reader = csv.reader(file)
no_header = next(reader, None)
new_dict = {}
for x in reader:
new_dict[int(x[0])] = Competition(int(x[0]), x[3], x[11], None,[])
print(new_dict)
部分輸出是:
{1903: 1903 2428 6 None [], 1904: 1904 2428 6 None [], 1905: 1905 2994 11 None [],
但我希望它是:
{1903: Competition(1903, 2428, 6, None, []), 1904: Competition(1904, 2428, 6, None, []), 1905: Competition(1905, 2994, 11, None, []),
那可能嗎?
當打印包含類的字典時,它會打印__repr__
函數的返回值。 因此,您可以簡單地使__repr__
函數如下(因為__str__
函數已經返回您想要的值):
def __repr__(self):
return self.__str__()
正如@Seth Peace 所說,問題是為了為您的類獲取字符串值,Python 會調用__repr__
如果已定義),而不是__str__
。
但是,更簡潔的方法是使用數據類:
from dataclasses import dataclass
from typing import Optional
@dataclass
class Competition:
year: int
distance: int
stages: int
winner: Optional[str]
cyclist: list
print(Competition(2019, 3, 5, "John Doe", []))
通過這樣做, __init__
、 __str__
和__repr__
已經以有意義的方式定義了。
當您打印容器時,它包括其元素的 repr。 問題是您交換了__str__
和__repr__
方法。
雖然,有沒有在具有獨立的多點__str__
如果它是幾乎一樣__repr__
只是寫了一個有點不同。 我會添加一些額外的信息,使其對最終用戶更有幫助。
同樣,您在__init__
混淆了類型注釋和默認值。 所有將類型作為默認值的都是不正確的。 只有winner
是正確的,但因為它有一個默認值而其他人沒有,所以它需要最后去。
class Competition:
def __init__(self, year: int, distance: int, stages: int, cyclist: list, winner=None):
self.year = year
self.distance = distance
self.stages = stages
self.cyclist = cyclist
self.winner = winner
def __repr__(self):
s = "Competition({}, {}, {}, {}, {})".format(
self.year,
self.distance,
self.stages,
self.cyclist,
self.winner
)
return s
def __str__(self):
s = "{}: {} km, {} stages, winner {} out of {})".format(
self.year,
self.distance,
self.stages,
self.winner,
self.cyclist,
)
return s
(您還缺少格式字符串中的右括號。)
然后實例化看起來像這樣:
year = int(x[0])
new_dict[year] = Competition(year, x[3], x[11], [])
例如:
c = Competition(1903, 2428, 6, [])
print(c) # -> 1903: 2428 km, 6 stages, winner None out of [])
print(repr(c)) # -> Competition(1903, 2428, 6, [], None)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.