3

I am switching from MATLAB to Python and numpy and I would like to know if there is any difference between the option to define a class method and the option to the function to a class field (instance variable)? Here is the example:

class MyClass:
    def __init__(self, a):            
        self.a=a    #some variable

    def add(self,b):
        return self.a+b

vs

class MyClass:
    def __init__(self, a):
        self.a=a    #some variable            
        self.add = lambda b: self.a+b

It works in both cases when I call

my_object=MyClass(2)
print(my_object.add(2)) #prints 4

Are there any differences between these two approaches? Any best practices/downsides? To me, the first one feels more "proper OOP", but the second one feels more flexible. Or, maybe, the definitions are identical, because of the way Python works under the hood?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
DIgg
  • 51
  • 2
  • The first one is a method, the second one is just a function that is an attribute. Note, for a method, a single function object on the class, whereas if you assign a function to an attribute, a separate function object exists for every instance. – juanpa.arrivillaga Jun 19 '20 at 20:12
  • 1
    Best practice is not to use a `lambda` function and assign it to a variable, see here: https://stackoverflow.com/questions/25010167/e731-do-not-assign-a-lambda-expression-use-a-def. – Dr. V Jun 19 '20 at 20:12

1 Answers1

2

The second one can't be overridden and takes a lot more space, because there's a separate function in every instance's __dict__ instead of one function in the class __dict__. (Instance method objects are created and reclaimed on the fly if you do it the normal way, or optimized out entirely in many cases depending on Python version.)

user2357112
  • 260,549
  • 28
  • 431
  • 505