Skip to content

Instantly share code, notes, and snippets.

@chrishavlin
Created March 17, 2022 17:44
Show Gist options
  • Save chrishavlin/dc0641da01df08b6df0d0f3cfc0689b0 to your computer and use it in GitHub Desktop.
Save chrishavlin/dc0641da01df08b6df0d0f3cfc0689b0 to your computer and use it in GitHub Desktop.
# running mypy on this file fails:
# error: Only concrete class can be given where "Type[Student]" is expected
import abc
import functools
# https://docs.python.org/3/library/functools.html#functools.total_ordering
@functools.total_ordering
class Student(abc.ABC):
def __init__(self, firstname: str, lastname: str):
self.firstname = firstname
self.lastname = lastname
def _is_valid_operand(self, other):
return (hasattr(other, "lastname") and
hasattr(other, "firstname"))
def __eq__(self, other):
if not self._is_valid_operand(other):
return NotImplemented
return ((self.lastname.lower(), self.firstname.lower()) ==
(other.lastname.lower(), other.firstname.lower()))
def __lt__(self, other):
if not self._is_valid_operand(other):
return NotImplemented
return ((self.lastname.lower(), self.firstname.lower()) <
(other.lastname.lower(), other.firstname.lower()))
@abc.abstractmethod
def get_record(self) -> str:
pass
class NewStudent(Student):
def get_record(self) -> str:
return f"{self.lastname}, {self.firstname}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment