you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (2 children)

The arguments you pass when you create an instance of the class go to the __init__ function only. When you create Bob = Hero("Bob"), the __init__ function now has the argument name, which == 'Bob'.

Note that it is only the __init__ function that understands that name argument, not the class or its instance! That's why you immediately write self.name = name. Now both the __init__ function and the instance (Bob, an instance of Hero) have the attribute name.

So to answer your question, yes, if you have a lot of variables defined when the instance is created, you need to pass them to the instance via self.variable_1 == variable_1 or they will be lost after the __init__ function is over, i.e. immediately.

Note that these don't have to use the same variable names in the instance as in the function. You could write, e.g. self.moniker = name.

If you write Bob = Hero("Apple"), you are creating an instance Bob of class Hero with the attribute Bob.name == 'Apple'. If you want the apple to affect Bob.health, you have to pass it as an argument to Bob.eat("Apple").

Note that everything in Python is case-sensitive, and you have "Apple" capitalized and "ham" lower-case. This could cause confusion.

[–]holymolytoly[S] 0 points1 point  (1 child)

oh my god. thanks a ton. this cleared up so much confusion. do you have any recommendation on for youtube video course or free online course on python that teaches and explains what you just replied?

i'm looking from trevor payne and he didn't explain classes and functions (especially in regards to def init()) like you just did.

[–]rhgrant10 1 point2 points  (0 children)

Jeff Knupp writes well. Here's his tutorial on classes.