I was thinking about writing a class decorator which would check whether a particular method inherited from object
had been overridden or not.
import io
def check_str_method(kls:type) -> type:
with io.StringIO() as strm:
if "__str__" in kls.__dict__:
print("`__str__` is in `__dict__`", file = strm)
if "__str__" in dir(kls):
print("`__str__` is in container returned by `dir(kls)`", file = strm)
str_method = getattr(kls, "__str__")
if str_method == object.__str__:
pass
if str_method == object.__str__:
pass
return kls
@check_str_method
class ChildClass1:
pass
@check_str_method
class ChildClass2:
def __str__(self):
return "I HAVE OVERRIDDEN __str__"
obj1 = ChildClass1()
obj2 = ChildClass2()
print("obj1...", str(obj1))
print("obj2...", str(obj2))
What is the proper pythonic way to do this? Do we check mro()
(the method resolution order?)
Do we search in __bases__
?