I was trying to override __str__
and __repr__
for class as shown in the code below. The new methods are called whenever I call the instance_method but the object calls for class_method remains the same (Please see the code snippet and the output below for clarity). Is there a way possible to override __str__
and __repr__
for @classmethod
so that the value of cls
can be changed?
I have also tried adding __str__
and __repr__
as @classmethod
but nothing changed.
class Abc:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Added {self.name}"
def __repr__(self):
return f"instance method repr"
def instance_method(self):
print(f"instance method {self}")
@classmethod
def __repr__(cls):
return f"class method"
@classmethod
def __str__(cls):
return f"class method"
@classmethod
def class_method(cls):
print(f"class method '{cls}'")
@staticmethod
def static_method():
print(f"static method")
def add(self, a: int,b: int,c: int) -> int:
return a+b+c
o = Abc("alpha")
o.class_method()
o.static_method()
o.instance_method()
Abc.static_method()
Abc.class_method()
print(o.add(1,2,3))
Output of the above code:
class method '<class '__main__.Abc'>'
static method
instance method class method
static method
class method '<class '__main__.Abc'>'
6