Pass all arguments of a function to another function

前端 未结 5 1541
感动是毒
感动是毒 2021-01-04 06:37

I want to have a class that I can create subclasses of that has a print function that only prints on a particular condition.

Here\'s basically what I\'m trying to do

5条回答
  •  迷失自我
    2021-01-04 07:20

    I know it looks a bit ugly but works perfectly, if you are using a lot of keyword arguments and only want to build a facade for another method:

    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'})
    

    Although it's a lot of boilerplate, it avoids any duplication of parameter statements.

    You might also look into using a decorator to make the conditional part more pythonic. But beware that the decorator checks the condition once prior to the class instantiation.

提交回复
热议问题