Hi,
I’m on Exercise 40 of “Learn Python the Hard Way” reading the HTML book text about Classes and Objects.
The mid-page discussion describes the need to include an init function to create a Class. The book text uses the example below:
class MyStuff(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print("I AM CLASSY APPLES!")
I’m confused about the role the __init_function plays in the creation of Classes and Objects. Clearly, the use of the self_tangerine variable and the lyric as a string assignment is just a random example to demonstrate init.
Yet it seems the existence of an init function of some kind is necessary to enable code to create any object from the class. The book text says as much in its step-by-step description under the “Objects are like Import” sub-head, where it says: “Python then looks to see if you made a “magic” init function, and if you have it calls that function to initialize your newly created empty object.”
In general, how does a programmer decide how to write the init function code? It seems anything would work, as long as it exists. That leaves an infinite number of possibilities – unless I’m completely confused and I may well be!
Thanks,
Mark
Also:
The 3 lines of code under “Objects are like Imports” have line numbers 1, 2 and 3. As a complete beginner, that confused me since it seemed like they represent a new .py file – like the other files I’ve been typing into my Atom text editor exercise by exercise. But in this case, these lines need to go underneath the class MyStuff(object) code above, so the line numbers would really be something like 10, 11, 12, etc.