Python允许类方法有多个输入参数吗?

1 投票
3 回答
2551 浏览
提问于 2025-04-18 16:05

我在网上找不到这个问题的答案。在Python中,我能否做到像这样:

class MyClass(object):
    """It's my class, yo!"""
    def __init__(self, string_of_interest_1):
        self.string1 = string_of_interest_1
        self.string2 = None
        self.int1 = None
    def __init__(self, string_of_interest_1, string_of_interest2):
        self.string1 = string_of_interest_1
        self.string2 = string_of_interest_2
        self.int1 = None
    def __init__(self, int_of_interest_1):
        self.string1 = None
        self.string2 = None
        self.int1 = int_of_interest_1

我把这个称为“方法重载”,但似乎标准的重载是指在调用时给一些变量赋默认值。(例如,def __init__(self, string_of_interest_1, string_of_interest_2 = None))虽然这个小例子没有展示出来,但我希望能够根据传入的参数数量和类型,拥有真正不同的方法。

谢谢!

3 个回答

1

你可以在函数中接收任意数量的参数,即使你的函数事先并不知道有多少个参数。要实现这一点,你可以使用一个星号(*)来表示可以接收多个参数;通常我们会用“args”这个词来表示。使用 *args 的好处是,你可以接收比你之前定义的正式参数更多的参数。想了解具体的例子,可以看看这个讨论帖。

*args 和 **kwargs 是什么?

1

在Python中,所有的变量都是对象,即使是int(整数)也是对象。

方法重写在CJAVA等语言中使用。

Python有一些特别的变量,叫做****用于位置参数,而**用于关键字参数。

试试这个

def test_method(*args, **kwargs):
    print args
    print kwargs

用不同的参数来调用这个函数,你会对这些特别的方法有更好的理解。

2

在Python中,函数或方法是不能重载的,但有一个变化,就是可以使用 *args 和 **kwargs。举个例子:

>>def test(*args, **kwargs):
>>    print args # list of positional parametrs
>>    print kwargs # dict of named parametrs

>>test(1, 2, test_param='t')
[1, 2]
{test_param: 't'}

撰写回答