Python类中创建带不同参数的同名Hello方法的实现疑问
在Python类中实现不同参数数量的同名方法
Python本身不支持传统意义上的方法重载——也就是不能直接定义两个同名但参数数量不同的方法,后定义的方法会直接覆盖之前的。不过我们可以通过几种变通方式实现你要的效果:
实现方案
1. 利用默认参数
给第二个参数设置默认值,通过判断参数是否为默认值来区分逻辑:
class Greeting: def Hello(self, arg1, arg2=None): if arg2 is None: print('This function is only having 1 argument') else: print('This function is having 2 arguments') # 调用测试 g = Greeting() g.Hello("foo") g.Hello("foo", "bar")
2. 使用可变参数(*args)
通过可变参数接收任意数量的输入,再根据参数个数执行对应逻辑:
class Greeting: def Hello(self, *args): if len(args) == 1: print('This function is only having 1 argument') elif len(args) == 2: print('This function is having 2 arguments') # 可扩展处理更多参数的情况 # 调用测试 g = Greeting() g.Hello("foo") g.Hello("foo", "bar")
3. 使用functools.singledispatchmethod
这个工具可以让你基于参数类型(或数量)实现类似重载的效果:
from functools import singledispatchmethod class Greeting: @singledispatchmethod def Hello(self, arg1): print('This function is only having 1 argument') @Hello.register def _(self, arg1, arg2): print('This function is having 2 arguments') # 调用测试 g = Greeting() g.Hello("foo") g.Hello("foo", "bar")
输出分析
以上三种方案调用后,输出结果完全一致:
This function is only having 1 argument This function is having 2 arguments
需要注意的是,如果你直接定义两个同名Hello方法,比如:
class Greeting: def Hello(self, arg1): print('This function is only having 1 argument') def Hello(self, arg1, arg2): print('This function is having 2 arguments')
此时第一个Hello方法会被第二个覆盖,调用g.Hello("foo")会直接报错,因为Python只会保留最后定义的那个方法。
内容的提问来源于stack exchange,提问作者Kailash Mishra
相关产品推荐
相关产品推荐

