Search code examples
pythonclasssyntaxclass-methodmagic-methods

What is the difference between using magic method of a class with following syntaxes in Python: method(member) and member.__method__()?


I created a class and specified the attributes of the member with the following code:

Mexico_66 = Product('Mexico 66 VIN', 99.90, 4)

In the class, I have defined the following magic method:

def __len__(self):
    print(self.quantity)

When I try to use this magic method with the following syntax: len(Mexico_66), the code executes but gives off an error at the very end: TypeError: 'NoneType' object cannot be interpreted as an integer

However, when executing the code with the following syntax: Mexico_66.len(), no error appears.

I don't quite understand why the error is caused in the first case and what is the difference between the 1st and 2nd options of executing magic method. I would be grateful if someone could explain it.


Solution

  • The __len__ magic method is supposed to return something, in this case, probably return self.quantity. You are getting the type error because your method implicitly returns None.

    The idea of using these magic methods is to define behavior for commonly used functions like len(). If you call it using instance.__len__(), you are not utilizing the magic method, you are simply calling it like a regular instance method, which is why you don't see any error in that use case