[英]How To Make Class Default Returning Value A Dictionary
I hope the title is clear enough for my purpose, to be honest I did not try much because I didn't really knew where to go to, and I'm not even sure this is totally possible. 我希望标题对我而言足够清晰,说实话,我没有做太多尝试,因为我并不真正知道该去哪里,而且我甚至不确定这是完全可能的。 I know its possible to override __str__
and __int__
to return values of those 2 types. 我知道有可能重写__str__
和__int__
返回这两种类型的值。 I sure you're asking 'why not have a class function to return what you want', and sure its a reasonable question, but I wanted a cleaner way to do it. 我确定您在问“为什么没有一个类函数返回您想要的东西”,并确定它是一个合理的问题,但是我想要一种更简洁的方法来实现。
I've searched for other similar questions and examples that might have helped but none really do what I intend. 我搜索了其他可能有助于解决问题的类似问题和示例,但没有一个能真正达到我的预期。 The closest I could get is from the example I tried below overriding __new__
and __repr__
. 我可以得到的最接近的示例来自下面覆盖__new__
和__repr__
。
class student:
def __init__(self, name, age):
self.info = {'name': name, 'age': age}
def __new__(self, name, age):
return self.info
def __repr__(self, name, age):
return self.info
student_data = student('Rob', 18)
print(student_data)
Thanks in advance 提前致谢
You were close. 你近了 Both __str__
and __repr__
must return a string. __str__
和__repr__
必须返回一个字符串。 print
will internally call your object's __str__
representation. print
将在内部调用对象的__str__
表示形式。 So, just have your __str__
method return the string representation of self.info
(IOW str(self.info)
). 因此,只需让您的__str__
方法返回__str__
的字符串表示self.info
(IOW str(self.info)
)。
class Student:
def __init__(self, name, age):
self.info = {'name': name, 'age': age}
def __repr__(self):
return str(self.info)
def __str__(self):
return self.__repr__()
student_data = Student('Rob', 18)
print(student_data)
# {'name': 'Rob', 'age': 18}
If your goal is to make an object act like a dictionary, you can subclass dict
itself, or perhaps even easier, subclass collections.UserDict
. 如果您的目标是使对象像字典一样工作,则可以对dict
本身进行子类化,或者甚至可以dict
类collections.UserDict
子类化。
import collections
class Student(collections.UserDict):
def __init__(self, name, age):
self.data = {'name': name, 'age': age}
student_data = Student('Rob', 18)
print(student_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.