2017-02-28 179 views
3

我想创建一个类,可以创建具有仅在特定条件下打印的打印函数的子类。将函数的所有参数传递给另一个函数

这里的基本上就是我想要做的事:

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

这个工程已经除了事实,有观点认为,必须与默认print功能明确指出,如end(例如: print('Hello, world!', end=''))。我怎样才能让我的新班级的print函数接受如end=''这样的参数并将它们传递给默认的print

+1

你可以使用'** kwargs' –

回答

5

标准的方式来传递对所有参数是@JohnColeman的建议评论:

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

args是非关键字(位置)参数的元组,并且kwargs是关键字参数的字典。

1

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

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

如果有人告诉我这个答案有什么问题使它值得赞赏,我很乐意解决这些问题。 – TigerhawkT3

+0

对于手头的问题,你的回答很好。有时候很难弄清楚降价。 –

+0

受到随意不喜欢的人的影响:<我觉得如果你不喜欢的东西,你必须发表评论,否则就像'我的代码不起作用'一样无益 –

1

结尾处这样

def print(self, *args, end=''): 

如果参数是动态的还是太多:

def print(self, *args, **kwargs): 
相关问题