You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询:Python3中下述代码是否实现多态?函数式多态定义探讨

Is This Python Code an Example of Polymorphism?

Absolutely—this code is a valid implementation of subtype polymorphism (also called inclusion polymorphism), one of the core forms of polymorphism in object-oriented programming. Let’s break down why:

What’s polymorphism here?

At its simplest, polymorphism means "many forms": a single interface (like your common_interface function) can interact with objects of different types, as long as those types follow a shared contract. In your case, the contract is having a func() method.

Let’s walk through your code:

  1. B and C are subtypes of A, so they inherit the func() method from their parent class.
  2. The common_interface function defines a generic, type-agnostic interface: it takes any object obj and calls obj.func(), with no hardcoded checks for whether obj is a B or C.
  3. When you pass instances of B and C to common_interface, the function works seamlessly because both types adhere to the required contract (they have func()).

A note on dynamic dispatch (the "visible" side of polymorphism)

Right now, since B and C don’t override func(), calling obj.func() runs the implementation from A for both. But if you modified your code to override func() in the subtypes:

class B(A):
    def func(self):
        print("Executing B's func")

class C(A):
    def func(self):
        print("Executing C's func")

Then common_interface(B()) would print "Executing B's func" and common_interface(C()) would print "Executing C's func". This is dynamic dispatch—where the correct method is chosen at runtime based on the object’s actual type. This is the more recognizable form of subtype polymorphism, but even without overriding, your original code still qualifies because it uses a generic interface to work across multiple types.

The key takeaway

Polymorphism isn’t just about overriding methods—it’s about decoupling the code that uses an object from the object’s specific type. Your common_interface function doesn’t care what type of object it receives; it only cares that the object responds to func(). That’s exactly the "universal interface" you’re asking about.

So to answer your question directly: Yes, this code is a genuine implementation of polymorphism, and you absolutely can call it that.

内容的提问来源于stack exchange,提问作者Eduard Grigoryev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:27:43