1. 使用继承和多态在Python中,多态性通常通过继承和重写方法来实现。通过定义一个基类,并在子类中重写基类的方法,可以实现同一方法名对应不同行为的特性。class Animal: def make...
在Python中,多态性通常通过继承和重写方法来实现。通过定义一个基类,并在子类中重写基类的方法,可以实现同一方法名对应不同行为的特性。
class Animal: def make_sound(self): pass
class Dog(Animal): def make_sound(self): return "汪汪汪"
class Cat(Animal): def make_sound(self): return "喵喵喵"
def make_sound(animals): for animal in animals: print(animal.make_sound())
# 使用多态
animals = [Dog(), Cat()]
make_sound(animals)在某些情况下,可以通过类型检查和条件语句来模拟多态性。
def add(x, y): if isinstance(x, int) and isinstance(y, int): return x + y elif isinstance(x, str) and isinstance(y, str): return x + y else: return "类型不匹配"
result1 = add(5, 3) # 整数相加
result2 = add("Hello", " World") # 字符串拼接
print(result1, result2)函数装饰器可以用来扩展函数的功能,同时保持函数名的多态性。
def log(func): def wrapper(*args, **kwargs): print(f"调用函数 {func.__name__},参数:{args}, 关键字参数:{kwargs}") return func(*args, **kwargs) return wrapper
@log
def add(x, y): return x + y
result = add(5, 3)
print(result)Python中的许多内置函数和方法已经实现了多态性。
def print_item(item): print(item)
items = [1, "Hello", 3.14]
for item in items: print_item(item)Python的函数式编程提供了许多工具来实现多态性,如map、filter和lambda函数。
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)通过以上五种技巧,可以在Python中轻松实现函数多态性,从而提高代码的灵活性和可扩展性。