I'm trying to sort objects in an array based on its' date. For this, I have overridden the sorted method. I'm not allowed to use key with sorted so that's why I'm doing the bubble sort. But previously when I have overridden methods like len I didn't have to add another parameter and for sorted, how would it work? I'm pretty sure I can't do self[i].publication_date. Every time I run the code I get the following error, '<' not supported between instances of 'Article' and 'Article' why doesn't my code address that error?
import datetime
class Article():
def __init__(self, title: str, author: str, publication_date: datetime.datetime, content: str):
self.title = title
self.author = author
self.publication_date = publication_date
self.content = content
def __sorted__(self, x):
print(x)
for passnum in range(len(x)-1, 0, -1):
for i in range(passnum):
if x[i].publication_date > x[i+1].publication_date:
temp = x[i].publication_date
x[i].publication_date = x[i+1].publication_date
x[i+1].publication_date = temp
print(x)
return x
kwargs = {"title": "a", "author": "b", "content": "c"}
articles = [
Article(
**kwargs, publication_date=datetime.datetime(2001, 7, 5)),
Article(
**kwargs, publication_date=datetime.datetime(1837, 4, 7)),
Article(
**kwargs, publication_date=datetime.datetime(2015, 8, 20)),
Article(
**kwargs, publication_date=datetime.datetime(1837, 4, 7)),
]
print(articles[1].publication_date) # prints 1837-04-07 00:00:00
print(sorted(articles))
__sorted__was a special method that would be used? It isn't, at all.