How to bind a constant parameter in Python?

后端 未结 2 1089
情深已故
情深已故 2021-01-23 07:47

I have got a class similar to

class C:
    def __init__(self, a):
        self.a = a
    def noParam(self):
        return self.a
    def withParam(self, b)
            


        
相关标签:
2条回答
  • 2021-01-23 08:07

    You want to use functools.partial:

    import functools
    
    instC = C(5.)
    meth = functools.partial(instC.withParam, 239)
    

    Then you can pass this method (bound with both your instance and the value 239):

    do_thing(meth)
    
    0 讨论(0)
  • 2021-01-23 08:13

    You can use lambda functions to bind parameters:

    meth = lambda: instC.withParam(239)

    0 讨论(0)
提交回复
热议问题