【问题标题】:python: set one function to take the same arguments as anotherpython:将一个函数设置为与另一个函数采用相同的参数
【发布时间】:2017-11-14 03:27:30
【问题描述】:

我有一个类的成员是另一个类的列表。所以我想要类似的东西

class primary_class:
    def __init__(self):
        self.slist = []
    def add_secondary_class(self, <arguments>):
        self.slist.append(secondary_class(<arguments>))

基本上,我希望能够传递 add_secondary_class 参数,就像我将它们传递给 secondary_class 构造函数一样。

【问题讨论】:

标签: python


【解决方案1】:
def add_secondary_class(self, *args):
    self.slist.append(secondary_class(*args))

或者,如果你有 kwargs

def add_secondary_class(self, **kwargs):
    self.slist.append(secondary_class(**kwargs))

【讨论】:

  • 唉,这不行。使用**kwargs,我最终得到TypeError: add_secondary_class() takes exactly 1 argument (8 given)
  • 你是怎么调用函数add_secondary_class()的?
  • a = primary_class(); a.add_secondary_class(&lt;args&gt;)
  • 带有kwargs(关键字参数),您需要将它们称为foo(bar=5, bar2='param2', bar3=[]),即带有关键字
  • 糟糕。忽略了我添加了一些没有关键字和一些关键字。 def add_secondary_class(self,*args,**kwargs): 完美运行。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-07-19
  • 2018-11-13
  • 2021-10-12
  • 2013-11-19
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多