Thank you very much for all previous posts, I find them very helpful.
So, I have combined them into the following code, please suggest if we can make more improvements…
Special thanks to patrickd314, we updated:
class SortedList(list):
def __init__(self, lst):
super().__init__(lst)
self.sort()
def append(self, value):
super().append(value)
self.sort()
def __str__(self):
return '''__str__ is giving us more output control!
Our output is: ''' + repr(self)
list_object = SortedList([4, 1, 5])
print(list_object)
# __str__ is giving us more output control!
# Our output is: [1, 4, 5]
list_object.append(2)
print(list_object)
# __str__ is giving us more output control!
# Our output is: [1, 2, 4, 5]
list_object.append(-1)
print(list_object)
# __str__ is giving us more output control!
# Our output is: [-1, 1, 2, 4, 5]
class SuperDict(dict):
def __getitem__(self, key):
try:
return "The value for key {key} is {value}!".format(key = key, value = super().__getitem__(key))
except KeyError:
return "This key does not exist in this dictionary!"
dic = {i : i**2 for i in range(1, 6)}
super_dic_object = SuperDict(dic)
print(super_dic_object)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(super_dic_object[2])
# The value for key 2 is 4!
print(super_dic_object[6])
# This key does not exist in this dictionary!
__str__ is giving us more output control!
Our output is: [-1, 1, 2, 4, 5, 8]
Remember, that you can also override the behavior of repr() by means of __repr__(), the general idea being that __str__() is supposed to give you “pretty print” output for the benefit of your user, while __repr__() should contain more detailed, “under-the-hood” information for your benefit, as the developer.
The “string” output of repr() is simply Python’s default. You can make it what you want. You could have a list of all the appends, for example, if you needed it.
Are you referring to repr()? Yes, that is the default behavior, to return a string representation of an object.
My point was that, if you create a class, then you have the ability (or even responsibility) to determine what a “string representation” of your object looks like.