So far, we have learned..
Input
class ApplicationInfo:
def set_info(self, name, company, major):
self.name = name
self.company = company
self.major = major
def print_neat(self):
print('----------------------------')
print('Name : ', self.name)
print('Company ', self.company)
print('Major : ', self.major)
print('----------------------------')
Input
application = ApplicationInfo()
application.set_info('Liam Gallagher', 'Uber', 'Biology')
application.print_neat()
Output
----------------------------
Name : Liam Gallagher
Company Uber
Major : Biology
----------------------------
This is the code that we used from the previous post. As we all know by now, to make instance we had to call the className() and add "." after the method to access the instance method.
You may also remember the metaphor used previously to describe the relationship between class (waffle machine) and instance (waffle).
Now, let us make extra special waffle - a "chocolate chip waffle". Although, I am no expert in making a waffle. The steps in making a chocolate chip waffle will be..
Let us again look at the code that we have written so far.
application = ApplicationInfo()
application.set_info('Liam Gallagher', 'Uber', 'Biology')
application.print_neat()
The code above rather seems like..
How can we add chocalate chips when making the waffle or precisely when creating the instance?
Constructor - init()
Python class has constructor method which is automatically called after the class is created.
Input
class makeClass:
def __init__(self):
print('Class Created !')
myClass = makeClass()
Output
Class Created !
At the moment when the instance is created, we see that the constructor method is automatically called.
Now, let us implement this into our ApplicationInfo class.
Input
class ApplicationInfo:
def __init__(self, name, company, major):
self.name = name
self.company = company
self.major = major
def print_neat(self):
print('----------------------------')
print('Name : ', self.name)
print('Company ', self.company)
print('Major : ', self.major)
print('----------------------------')
Input
application = ApplicationInfo()
Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-41e426f145dc> in <module>
----> 1 application = ApplicationInfo()
TypeError: __init__() missing 3 required positional arguments: 'name', 'company', and 'major'
Since we did not add arguments inside the costructor method, error occurs in the process. Instead, we will pass three arguments as the constructor method is designed.
Input
application = ApplicationInfo("Randy Newman", "Pixar", "Aerospace Engineering")
application.print_neat()
Output
----------------------------
Name : Randy Newman
Company Pixar
Major : Aerospace Engineering
----------------------------