Method vs function-valued field in Python

Viewed 69

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?

1 Answers

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.)

Related