–Sorry if this is a double-post. I didn’t see it posted as a new topic.–
Hi,
Still working through this terrific book! Very helpful stuff.
Here’s a question I hope doesn’t put a Dunce Cap on my head. I’m struggling with it and have Googled various discussions on the web but am still a bit confused.
I’m confused why some Classes are coded without an “init” method and why others have an “init” method. (The underscores aren’t showing up in the post here, but I am typing them)
The code in Exercise 44 is one example. Parent and Child Classes are defined and dad and son objects are created but init is not used anywhere.
When I first read about Classes and Objects, I thought init was essential to creating objects from classes, but Exercise 44 code, and other code used in the book, works without the init.
Thanks in advance for any takers on my basic question.
-Mark (Destined to be a Python Expert, but right now, candidly, barely a beginner).
It is just a method where you assign properties to instances of classes
for example:
class Person(object):
def __init__(self, name, age, political_orientation):
self.name = name
self.age = name
self.political_orientation = political_orientation
doug = Person("Doug", 26, "Conservative")
# doug is a Person, his name is "Doug", he is 26 years old, he is a Conservative
print(doug.name) # prints "Doug"
print(doug.age) # prints 26
print(doug.political_orientation) # prints "Conservative"
If you don’t want a class to have any properties, you don’t need the: __init__
A class can just have functionality. So in the case of the Parent class from ex44:
class Parent(object):
def implicit(self):
print("PARENT implicit()")