Static lambdas in python

I have a class in python like this

import numpy as np class BackPropogationNetwork: # Static lambdas sigmoid = lambda x : 1/(1+np.exp(-x)) sigmoid_prime = lambda sigmoid: sigmoid(1-sigmoid) 

and this is contructor

  def __init__(self): self.some_attr = self.sigmoid(2) 

I get this error

 TypeError: <lambda>() takes exactly 1 argument (2 given) 

If I call it

 self.some_attr = ClassName.sigmoid() 

I get this error

 TypeError: unbound method <lambda>() must be called with BackPropogationNetwork instance as first argument (got int instance instead) 
+5
source share
3 answers

You need to wrap lambdas in staticmethod objects :

 class BackPropogationNetwork: sigmoid = staticmethod(lambda x : 1/(1+np.exp(-x))) sigmoid_prime = staticmethod(lambda sigmoid: sigmoid(1-sigmoid)) 

lambda expressions still produce function objects, simply using different (limited) syntax. The same rules apply as defining functions in a class; if you want this to be a static method, you still need to wrap them.

+4
source

So, your sigmoid function does not depend on the class, it makes sense to save it outside if:

  • you want not to pollute the module namespace
  • you want to increase the openness of the function
  • you want this method to be overwritten. Suppose you decide that you don’t change anything, well, in this case, you can do it. When you call a method like self.method() , python passes the first funtion argument to the self instance, so either you can make your lambda look like this: sigmoid = lambda self, x : 1/(1+np.exp(-x)) or you can do what others suggested how to make it staticmethod, since staticmethod is a decorator (a function that takes a function), you can call it like this

     In [1]: class A: ...: s = staticmethod(lambda x: x) ...: def a(self): ...: print self.s(10) ...: In [2]: f = A() In [3]: fa() 10 
+2
source

Your two sigmoid are not class methods. This means that when you call them, they expect Class to be the implicit first argument.

This error

 TypeError: <lambda>() takes exactly 1 argument (2 given) 

happens on this call

 self.some_attr = self.sigmoid(2) 

because the class instance object is passed implicitly along with int 2. But your sigmoid is defined to accept only one argument.

And I don’t think you will get this error

 TypeError: unbound method <lambda>() must be called with BackPropogationNetwork instance as first argument (got int instance instead) 

with this challenge

 self.some_attr = ClassName.sigmoid() 

The error you should get should be something like.

 TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'type' 

You may have made a mistake while pasting when entering a question.

0
source

Source: https://habr.com/ru/post/1234387/


All Articles