Reputation: 33
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. 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__
.
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
Upvotes: 0
Views: 613
Reputation: 2545
If your goal is to make an object act like a dictionary, you can subclass dict
itself, or perhaps even easier, subclass 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)
Upvotes: 0
Reputation: 402423
You were close. Both __str__
and __repr__
must return a string. print
will internally call your object's __str__
representation. So, just have your __str__
method return the string representation of 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}
Upvotes: 1