It's bad because it isn't friendly to other objects that act like your class.

You should use hasattr instead to check that the object you are working with is appropriate. That way as long as the object has the required attribute or method it will work with your code as well as your own objects. (If it is a method it still must accept the appropriate arguments.)

class YourClass:

    def required_method(self):

class MyClass:

    def required_method(self):

yourobj = YourClass()
myobj = MyClass()

isinstance(yourobj, YourClass)    #True
isinstance(myobj, YourClass)    #False
hasattr(yourobj, 'required_method')    #True
hasattr(myobj, 'required_method')    #True

Talking about inheritance, isinstance() might be somewhat confusing to beginners when it comes to an inherited class ...

class Class1:
    def method1(self):
class Class2(Class1):
    def method1(self):

c1 = Class1()
c2 = Class2()

print( isinstance(c1, Class1) )  # True
print( isinstance(c1, Class2) )  # False
print( isinstance(c2, Class1) )  # True --> Class1 is inherited
print( isinstance(c2, Class2) )  # True

If I have another object that's different from the type i want and have the same method name but does different things, it might screw up the process of the API.

Can you give concrete example of the API (You can have alternative input by having keyword parameters, inputstring='', inputlist=[], also you can use parameter "iterized": give parameter (inputstring,) or [inputstring] instead of inputstring)

This article has been dead for over six months. Start a new discussion instead.