I am a Python beginner grinding through Python Crash Course by Eric Matthes. I am currently on chapter 9 Classes and Object Oriented Programming.
I have the following code:
class User: # Define the class
"""A simple attempt to model website users."""
def __init__(self, first_name, last_name, age, username, city, country):
self.first_name = first_name.title()
self.last_name = last_name.title()
self.age = age
self.username = username
self.city = city.title()
self.country = country.title()
self.login_attempts = 0
I understand that Python calls the __init__() method to create a new instance, stores the first_name, last_name, age, username, city, and country attributes. The author says that Python creates a new attribute called login_attempts.
The author only shows this method, but I’ve seen some people online explicitly write the login_attempts attribute inside the __init__() method. Is there any difference between the two approaches? Is one of the approaches considered a "best practice?" I’d like to build good habits before I inconvenience people who use my code. Thank you!
>Solution :
It depends on the class. If you add login_attempts=0 in the argument list, that would allow a caller to specify their own value. However, many variables defined in __init__ are for internal use, and there is no point in allowing them to be overridden. Also, remember that if you JUST add login_attempts by itself, then the caller MUST supply a value. That’s why I added the default (=0).