I want to dynamically implement __str__ method on a object if the object doesn't already implement it.
I try using hasattr(obj, '__str__') it always returns me true as it picks it up from object class.
Is there a way to determine if an object actually implements __str__ ?
I know I can use inspect.getmembers(obj) but I am searching for a more pythonic way
EDIT
class Employee(object):
def __init__(self, name, age, emp_code):
self.name = name
self.age = age
self.emp_code = emp_code
Test
e = Employee("A", 23, "E1")
print hasattr(e, '__str__')
>> True
I want a check that returns False instead of picking up the method inherited from object.
Since what you want to check is if it has a __str__ implementation that is not the default object.__str__. Therefore, you can do this:
Foo.__str__ is not object.__str__
To check with instantiated objects you need to check on the class:
type(f).__str__ is not object.__str__
This will also work even if Foo doesn't implement __str__ directly, but inherited it from another class than object, which seems to be what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With