在python的一个类中具有相同名称的方法? [英] Methods with the same name in one class in python?

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

问题描述

如何在一个类中声明很少几个具有相同名称,但具有不同数量的参数或不同类型的方法?

How to declare few methods with the same name ,but with different numbers of parameters or different types in one class?

在本课中我必须更改的内容:

What I must to change in this class:

class MyClass:
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
    def my_method(self,parameter_A_that_Must_Be_String):
        print parameter_A_that_Must_Be_String

    def my_method(self,parameter_A_that_Must_Be_String,parameter_B_that_Must_Be_String):
        print parameter_A_that_Must_Be_String
        print parameter_B_that_Must_Be_String

    def my_method(self,parameter_A_that_Must_Be_String,parameter_A_that_Must_Be_Int):
        print parameter_A_that_Must_Be_String * parameter_A_that_Must_Be_Int

推荐答案

您可以使用一个函数,该函数接受可变数量的参数.

You can have a function that takes in variable number of arguments.

def my_method(*args, **kwds):
    # do something

# when you call the method
my_method(a1, a2, k1=a3, k2=a4)

# you get: 
args = (a1, a2)
kwds = {'k1':a3, 'k2':a4}

因此,您可以按以下方式修改函数:

So you can modify your function as follows:

def my_method(*args):
    if len(args) == 1 and isinstance(args[0], str):
        # case 1
    elif len(args) == 2 and isinstance(args[1], int):
        # case 2 
    elif len(args) == 2 and isinstance(args[1], str):
        # case 3

这篇关于在python的一个类中具有相同名称的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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