Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách overload (nạp chồng) hàm trong Python

Python không hỗ trợ method overloading truyền thống (cùng tên, khác signature). Hàm định nghĩa sau ghi đè hàm trước.

Giải pháp: Default arguments

class Human:
    def sayHello(self, name=None):
        if name is not None:
            print('Hello ' + name)
        else:
            print('Hello')

obj = Human()
obj.sayHello()           # Hello
obj.sayHello('Rambo')    # Hello Rambo

Đầu ra

Hello
Hello Rambo

Giải pháp: *args, **kwargs

def flexible(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

flexible(1, 2)
flexible(a=1, b=2)
flexible(1, 2, c=3)

Giải pháp: Type-based dispatch (Python 3.4+)

from functools import singledispatch

@singledispatch
def process(data):
    print("Default:", data)

@process.register(int)
def _(data):
    print("Integer:", data * 2)

@process.register(str)
def _(data):
    print("String:", data.upper())

process(10)      # Integer: 20
process("hi")    # String: HI
process([1,2])   # Default: [1, 2]

Giải pháp: Multiple dispatch library

Thư viện multipledispatch hoặc plum-dispatch cho overloading phức tạp.