python中的方法重载 [英] method overloading in python

查看:206
本文介绍了python中的方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调用未参数化的方法first,但还要调用参数化的first,但它给出了错误.

I need to call unparameterised method first, but also parameterized first, but it is giving an error.

>>> class A:
...     def first(self):
...             print 'first method'
...     def first(self,f):
...             print 'first met',f
...
>>> a=A()
>>> a.first()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: first() takes exactly 2 arguments (1 given) 

是否可以像在Java中那样在Python中进行方法重载?

Is it possible to do method overloading in Python like in Java?

推荐答案

您的第二个first方法将覆盖原始的first方法.在Python中,无法像在Java中那样创建重载方法.

Your second first method is overriding the original first method. In Python, it is not possible to create overloaded methods the same way as in Java.

但是,您可以创建带有可选和/或基于关键字的参数的方法,并进行相应的处理.这是一个示例:

However, you can create methods with optional and/or keyword-based arguments and process those accordingly. Here's an example:

class A:
    def first(self, f=None):
        if f is not None:
            print 'first met', f
        else:
            print 'first method'

用法:

a = A()
a.first()
a.first('something')

这篇关于python中的方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆