Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将函数的所有参数传递给另一个函数_Python - Fatal编程技术网

Python 将函数的所有参数传递给另一个函数

Python 将函数的所有参数传递给另一个函数,python,Python,我想有一个类,我可以创建它的子类,它有一个打印函数,只在特定条件下打印 以下是我想做的: class ClassWithPrintFunctionAndReallyBadName: ... def print(self, *args): if self.condition: print(*args) 这已经起作用了,但有一些参数必须使用默认的print函数显式声明,例如end(例如:print('Hello,world!',end='')

我想有一个类,我可以创建它的子类,它有一个打印函数,只在特定条件下打印

以下是我想做的:

class ClassWithPrintFunctionAndReallyBadName:
    ...
    def print(self, *args):
        if self.condition:
            print(*args)

这已经起作用了,但有一些参数必须使用默认的
print
函数显式声明,例如
end
(例如:
print('Hello,world!',end='')
)。如何使新类的
print
函数接受参数,例如
end='
,并将它们传递给默认的
print

只需复制方法签名的命名参数即可

def print(self, *args, end='\n', sep=' ', flush=False, file=None):
    if self.condition:
        print(*args, end=end, sep=sep, flush=flush, file=file)

像这样加在末尾

def print(self, *args, end=''):
如果参数是动态的或太多:

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

传递所有参数的标准方法是@JohnColeman在评论中建议的:

class ClassWithPrintFunctionAndReallyBadName:
    ...
    def print(self, *args, **kwargs):
        if self.condition:
            print(*args, **kwargs)
作为参数,
*args
接收非关键字(位置)参数的元组,
**kwargs
是关键字参数的字典


当使用
*
***
调用函数时,前一个元组被展开,就好像参数是单独传递的一样,后一个字典被展开,就好像它们是关键字参数一样。

我知道它看起来有点难看,但效果很好,如果您使用了大量关键字参数,并且只想为另一个方法构建外观:

def print(self, print_message, end='\n', sep=' ', flush=False, file=None):
    if self.condition:
        print(**{key: value for key, value in locals().items() if key not in 'self'})
尽管它是大量的样板文件,但它避免了参数语句的任何重复

您还可以考虑使用装饰器使条件部分更具python风格。但是要注意,装饰程序在类实例化之前检查一次条件。

类列表(列表):
def附加两次(self、*args、**kwargs):
self.append(*args,**kwargs)
self.append(*args,**kwargs)
l=List()
l、 附加两次(“你好”)
打印(l)#[“你好”,“你好”]

你可以使用
**kwargs
如果有人告诉我这个答案有什么问题,让我投反对票,我很乐意解决这些问题。你的答案对眼前的问题很好。有时很难找出反对票。被随机的不喜欢者所打动:<我觉得如果你不喜欢某样东西,如果没有,你就必须发表评论,否则它就像“我的代码不起作用”一样没有帮助questions@TigerhawkT3,与args和kargs解决方案相比,您的anwser无法推广。因此,最好在这些之后再向用户展示。这可能是投反对票的原因。