Python 多态与动态绑定

本文介绍了一个关于几何对象类的设计案例,包括圆形和矩形类的定义及其属性和方法。通过继承和方法覆盖实现了不同几何形状的统一管理和比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# coding: utf-8
class Geometricobject:
    def __init__(self, color = "green", filled = "True"):
        self.__color = color
        self.__filled = filled

    def getcolor(self):
        return self.__color

    def setcolor(self, color):
        self.__color = color

    def isfilled(self):
        return self.__filled

    def setfilled(self, filled):
        self.__filled = filled

    def __str__(self):
        return "color: " + self.__color + \
            " and filled: " + str(self.__filled)
# coding: utf-8
from GeometricObject import Geometricobject
import math

class Circle(Geometricobject):
    def __init__(self, radius):
       Geometricobject.__init__(self)
       self.__radius = radius

    def getRadius(self):
        return self.__radius

    def setRadius(self, radius):
        self.__radius = radius

    def getArea(self):
        return self.__radius * self.__radius * math.pi

    def getDiameter(self):
        return 2 * self.__radius

    def getPerimeter(self):
        return 2 * self.__radius * math.pi

    def printCircle(self):
        print self.__str__() + "radius: " +  str(self.__radius)

    # Override the __str__() method defined in GeometricObject
    def __str__(self):
        return Geometricobject.__str__(self) + " radius: " + str(self.__radius)
from GeometricObject import Geometricobject

class Rectangle(Geometricobject):
    def __init__(self, width = 1, height = 2):
        Geometricobject.__init__(self)
        self.__width = width
        self.__height = height

    def getWidth(self):
        return self.__width

    def setWidth(self, width):
        self.__width = width

    def getHeight(self, height):
        return self.__height

    def setHeight(self, height):
        self.__height = height

    def getArea(self):
        return self.__width * self.__height

    def getPerimeter(self):
        return 2 * (self.__width + self.__height)

    # Override the __str__ method defined in GeometricObject
    def __str__(self):
        return Geometricobject.__str__(self) + " width: " + \
            str(self.__width) + " height: " + str(self.__height)
# coding: utf-8
from CircleFromGeometricObject import Circle
from RectangleFromGeometricObject import Rectangle

def main():
    # Display circle and rectangle properties
    c = Circle(4)
    r = Rectangle(1, 3)
    displayObject(c)
    displayObject(r)
    print "Are the circle and rectangle the same size? " , \
    isSameArea(c, r)

# Display geometric object properties
def displayObject(g):
    print g.__str__()

# Compare the areas of two geometric objects
def isSameArea(g1, g2):
    return g1.getArea() == g2.getArea()

main()

在这个例子中,c是Circle类的一个对象。Circle类是GeometricObject类的子类。str()方法在这两个类中都有定义。因此,在displayObject方法中g应当调用哪个str()方法?g应当调用哪个str()方法由 动态绑定 决定。
动态绑定的机制如下: 假设对象o是类C1,C2,C3,…,Cn(C1是C2的子类,C2是C3的子类,… ,Cn-1 是 Cn 的子类,即Cn是通用的类,C1是最特定的类)的实例。在Python中,Cn是Object类。如果对象o调用一个方法p,那么Python会依次在类C1,C2,…,Cn中查找方法p的实现,直到找到为止。一旦找到一个实现,就会停止查找然后调用这个第一次找到的实现。

### Python 中的多态概念及其实现 #### 多态的概念 多态是指不同的对象可以对相同的消息做出不同的响应[^2]。具体来说,在面向对象编程中,子类可以通过继承父类并重写其方法来改变行为。这种特性使得同一个接口可以在多个类中有不同的实现形式。 #### 实现方式 在 Python 中,多态主要通过 **继承** **方法重写** 来实现。当一个基类被其他子类继承时,这些子类可以选择性地覆盖某些方法以提供特定的功能。此外,Python 的动态类型系统也支持鸭子类型(Duck Typing),这意味着只要对象实现了所需的方法或属性,就可以视为兼容而无需显式的继承关系[^3]。 以下是具体的实现示例: --- ### 示例代码:基于继承方法重写的多态 ```python class Animal: def speak(self): raise NotImplementedError("Subclasses must implement this method") class Dog(Animal): def speak(self): # 方法重写 return "Woof!" class Cat(Animal): def speak(self): # 方法重写 return "Meow!" def make_animal_speak(animal: Animal): print(f"The animal says {animal.speak()}") # 调用统一接口 dog = Dog() cat = Cat() make_animal_speak(dog) # 输出: The animal says Woof! make_animal_speak(cat) # 输出: The animal says Meow! ``` 在这个例子中,`Dog` `Cat` 类都继承自 `Animal` 基类,并各自重写了 `speak()` 方法。尽管两个类的具体实现不同,但在外部调用时仍然可以通过相同的接口访问它们的行为[^4]。 --- ### 示例代码:利用鸭子类型的多态 即使没有明确的继承关系,只要对象提供了预期的方法签名,也可以表现出多态性: ```python class Car: def start_engine(self): return "Vroom! Engine started." class Bicycle: def start_engine(self): # 非继承情况下仍能模拟相似功能 return "Pedal power activated!" def vehicle_action(vehicle): print(vehicle.start_engine()) # 统一调用逻辑 car = Car() bicycle = Bicycle() vehicle_action(car) # 输出: Vroom! Engine started. vehicle_action(bicycle) # 输出: Pedal power activated! ``` 这里展示了如何不依赖于严格的继承体系也能达到多态的效果——这得益于 Python动态绑定的支持。 --- ### 总结 - 多态的核心在于让不同的对象能够对外呈现一致的操作界面,但内部处理却各有差异。 - 它通常借助继承方法重载完成;同时由于 Python 支持鸭子类型,因此即便不存在直接关联也可展现类似的灵活性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值