[英]Have the class as value in a dictionary
I have a class:我有一堂课:
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)
And I want to add the class to a dictionary as the value, and as key the years.我想将该类添加到字典中作为值,并作为年份的关键。 The information I get is from a file.
我得到的信息来自一个文件。
So I have this所以我有这个
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)
Part of the output is:部分输出是:
{1903: 1903 2428 6 None [], 1904: 1904 2428 6 None [], 1905: 1905 2994 11 None [],
But I would like it as:但我希望它是:
{1903: Competition(1903, 2428, 6, None, []), 1904: Competition(1904, 2428, 6, None, []), 1905: Competition(1905, 2994, 11, None, []),
Is that possible?那可能吗?
When printing dictionaries with classes in them, it will print the return value of the __repr__
function.当打印包含类的字典时,它会打印
__repr__
函数的返回值。 Therefore, you can simply make the __repr__
function as follows (since the __str__
function is already returning the value that you want):因此,您可以简单地使
__repr__
函数如下(因为__str__
函数已经返回您想要的值):
def __repr__(self):
return self.__str__()
As @Seth Peace said, the thing is that in order to get a string value for your class, Python calls __repr__
if it is defined, not __str__
.正如@Seth Peace 所说,问题是为了为您的类获取字符串值,Python 会调用
__repr__
如果已定义),而不是__str__
。
However, a cleaner way to do this can be to use a dataclass:但是,更简洁的方法是使用数据类:
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", []))
By doing so, __init__
, __str__
and __repr__
will already have been defined in a meaningful way.通过这样做,
__init__
、 __str__
和__repr__
已经以有意义的方式定义了。
When you print a container, it includes the repr of its elements.当您打印容器时,它包括其元素的 repr。 The problem is that you've swapped the
__str__
and __repr__
methods.问题是您交换了
__str__
和__repr__
方法。
Although, there's not much point in having a separate __str__
if it's practically the same as __repr__
just written a bit different.虽然,有没有在具有独立的多点
__str__
如果它是几乎一样__repr__
只是写了一个有点不同。 I would add some additional info to make it more helpful to an end user.我会添加一些额外的信息,使其对最终用户更有帮助。
As well, you've mixed up type annotations and default values in __init__
.同样,您在
__init__
混淆了类型注释和默认值。 All the ones that have a type as their default value are incorrect.所有将类型作为默认值的都是不正确的。 Only
winner
is correct, but because it has a default and the others don't, it needs to go at the end.只有
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
(You were also missing a closing parenthesis inside the format string.) (您还缺少格式字符串中的右括号。)
And then instantiation would look like this:然后实例化看起来像这样:
year = int(x[0])
new_dict[year] = Competition(year, x[3], x[11], [])
For example:例如:
c = Competition(1903, 2428, 6, [])
print(c) # -> 1903: 2428 km, 6 stages, winner None out of [])
print(repr(c)) # -> Competition(1903, 2428, 6, [], None)
You cannot have the class as a value in this way.您不能以这种方式将类作为值。 You sure can pass a reference to the class itself, but having it this way (
Competition(1903, 2428, 6, None, [])
) what you actually want is to print an object - an instance to a class .您当然可以传递对类本身的引用,但是通过这种方式(
Competition(1903, 2428, 6, None, [])
)您真正想要的是打印一个对象 -一个类的实例。 So, if you want to print a string that is like the desired output you should do something like you already did with __str__
, but it will be a string (enclosed in quotes) instead of the declarative class form.因此,如果您想打印一个类似于所需输出的字符串,您应该像使用
__str__
那样做一些事情,但它将是一个字符串(用引号括起来)而不是声明性的类形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.