通过显式调用对象的名称将多个*arg(或**kwarg)传递给对象

2024-06-26 04:29:02 发布

您现在位置:Python中文网/ 问答频道 /正文

当我学习Python中的*arg和**kwargs时,我想到了这个问题。举个例子:

class Person1():
    def __init__(self, name, age, *petdogs):
        self.name = name
        self.age = age
        self.petdogs = list(petdogs)

    def show_dogs(self):
        for petdog in self.petdogs:
            print(petdog)
Dummy = Person1("Dummy", 16, "A", "B", "C")
Dummy.show_dogs()
#Output:
#A
#B
#C

是否可以将多个*和**参数传递给一个对象?

以下是我尝试过的:

class Person2():
    def __init__(self, name, age, *petdogs, *petcats):
        self.name = name
        self.age = age
        self.petdogs = list(petdogs)
        self.petcats = list(petcats)
    def show_dogs(self):
        for petdog in self.petdogs:
            print(petdog)
    def show_cats(self):
        for petcat in self.petcats:
            print(petcats)

然后

Dummy2 = Person2(name = "Dummy", age = 16, petdogs = ("A", "B", "C"), petcats = ("D", "E"))
print("pet dogs:")
Dummy2.show_dogs()
print("pet cats:")
Dummy2.show_cats()

我想看到输出像上面的例子一样

pet dogs:
A
B
C
pet cats:
D
E

当然它不起作用,但我想知道是否有一种方法可以通过使用*


Tags: nameselfforagedefshowlistdummy
1条回答
网友
1楼 · 发布于 2024-06-26 04:29:02

*args构造在函数中充当传递的其余参数的占位符,因此不能有两个“其余参数占位符”,因为技术上只有一个“其余参数”。 示例:

def f(a, b, *args):
    print(f'a = {a}, b = {b}, rest = {args}')

f(1, 2, 3, 4, 5, 6) # => a = 1, b = 2, rest = (3, 4, 5, 6)

**kwargs在本质上类似,但适用于以keyword=value方式传递的参数:传递的任何关键字参数的其余部分将以名称kwargsdict形式显示在函数中。 示例:

def f(a, b, c, *args, **kwargs):
    print(f'a = {a}, b = {b}, rest = {args}, rest-kw = {kwargs}')

f(1, 2, 3, 4, 5, 6, d=7, e=8) #=> a = 1, b = 2, rest = (3, 4, 5, 6), rest-kw = {'d': 7, 'e': 8}

对于你想做的事情,从技术上讲,你不想表达“休息”,因此你可以:

class Person2():
    def __init__(self, name, age, petdogs, petcats):
        self.name = name
        self.age = age
        self.petdogs = list(petdogs)
        self.petcats = list(petcats)
    def show_dogs(self):
        for petdog in self.petdogs:
            print(petdog)
    def show_cats(self):
        for petcat in self.petcats:
            print(petcats)

Dummy2 = Person2(name = "Dummy", age = 16, petdogs = ("A", "B", "C"), petcats = ("D", "E"))
print("pet dogs:")
Dummy2.show_dogs()
print("pet cats:")
Dummy2.show_cats()

会很好的

相关问题 更多 >