Is it necessary to use an 'if' statement here?

Viewed 68

Example 6-3 of Fluent Python defines a private variable self.__total and uses an if statement prior to its assignment seen as below:

if not hasattr(self, '__total'):            
    self.__total = sum(item.total() for item in self.cart)        
return self.__total

Why not just use the statement return self.__total = sum(item.total() for item in self.cart) to make the assignment?

1 Answers

There is a difference, doing

return self.__total = sum(item.total() for item in self.cart)

will overwrite any previous value private variable total holds, whereas,

if not hasattr(self, '__total'):            
    self.__total = sum(item.total() for item in self.cart)        
return self.__total

will return the previous value if it was assigned before...

Related