How does polymorphism work in Python?

前端 未结 4 1382
慢半拍i
慢半拍i 2020-12-02 15:31

I\'m new to Python... and coming from a mostly Java background, if that accounts for anything.

I\'m trying to understand polymorphism in Python. Maybe the problem is

4条回答
  •  一向
    一向 (楼主)
    2020-12-02 15:52

    The is operator in Python checks that the two arguments refer to the same object in memory; it is not like the is operator in C#.

    From the docs:

    The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

    What you're looking for in this case is isinstance.

    Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof.

    >>> class animal(object): pass
    
    >>> class dog(animal): pass
    
    >>> myDog = dog()
    >>> isinstance(myDog, dog)
    True
    >>> isinstance(myDog, animal)
    True
    

    However, idiomatic Python dictates that you (almost) never do type-checking, but instead rely on duck-typing for polymorphic behavior. There's nothing wrong with using isinstance to understand inheritance, but it should generally be avoided in "production" code.

提交回复
热议问题