r/learnpython • • Feb 23 '21

Classes. Please explain like I’m 5.

What exactly do they do? Why are they important? When do you know to use one? I’ve been learning for a few months, and it seems like, I just can’t wrap my head around this. I feel like it’s not as complicated as I’m making it, in my own mind. Thanks.

229 Upvotes

71 comments sorted by

View all comments

Show parent comment

5

u/LiquidLogic Feb 24 '21

Great explanation! Thanks for posting it!

I was wondering what the '=None' is for, and why it is after date_opened?

5

u/[deleted] Feb 24 '21 edited Feb 24 '21

When you define a function whose parameter has =something, that becomes the default value if you do not pass an argument in.

Try running these to see what that means.

# no default argument, pass in value
def greet1(name):
    print("Hello", name)

greet1("Binwin")


# default argument, pass in value
def greet2(name="fellow adventurer"):
    print("Hello", name)

greet2("Binwin")


# no default argument, no passed in argument
def greet3(name):
    print("Hello", name)

greet3()


# default argument, no passed in argument
def greet4(name="fellow adventurer"):
    print("Hello", name)

greet4()

The reason I added a =None here is because if this were actually a function used by an ATM or bank, then when you created an account, you'd probably want to set the date_opened value to the current timestamp (hence the datetime.datetime.today()). But I gave the option of passing in something else in case you wanted to retroactively create an account for someone.

1

u/LiquidLogic Feb 24 '21

that becomes the default value if you do not pass an argument in.

Ah, this makes sense. I just ran through your examples in Repl.it, I see the TypeErrors occuring when you don't pass an argument.

I see how adding =None would allow you to add in the date_opened later on if you didnt pass the argument and would prevent an error.

Thanks for taking the time to explain! :)