Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีทำ Function Overloading ใน Python

Python ไม่รองรับ method overloading แบบดั้งเดิม (หลายฟังก์ชันชื่อเดียวต่าง signature) แต่ทำได้ด้วย default arguments หรือ type checking ภายในฟังก์ชัน

ตัวอย่างด้วย default argument

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

กำหนดพารามิเตอร์ optional ด้วย =None แล้วตรวจสอบภายในฟังก์ชัน นี่คือวิธีมาตรฐานใน Python