Constructor | COMP70050: Introduction to Machine Learning | Department of Computing | Imperial College London home article Introduction to Machine Learning COMP70050 Autumn Term 2021/2022 Introduction to Python for Java programmers The Zen of Python Example Python program Python vs. Java - Main method Python vs. Java - Variable declaration Python vs. Java - Semicolons Python vs. Java - Braces Python vs. Java - Comments Running Python Running Python as a script Running Python interactively Basic built-in data types Everything is an object Reserved words Variables - Java vs. Python Python Variables Objects in Python Operators Assignment operator Lists Accessing Lists Modifying Lists Tuples Strings are sequences Formatting strings Sets Dictionaries Grouping data with dict and tuple Control flow Loops Useful objects for loops List comprehensions Functions Function arguments Built-in functions Object-Oriented Programming in Python Constructor Attributes Methods Magic/Dunder methods Inheritance Encapsulation Encapsulation the Pythonic way What about protected? Python modules Custom modules What's in a __name__? Handling text files Reading CSV files Writing to CSV files Handling JSON files Pickle That's a wrap! Constructor Let us first look at the __init__() method. The double underscores on both sides is a Python convention that indicates that this is a magic method that does special things. They are called magic or dunder methods (dunder == double underscores). We will see more of these later. 1
2
3
4
5
6
7
class Person:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
person = Person("Josiah", "Wang", 20) # invoking the constructor
__init__() acts as the constructor. When you create a class instance (Line 7), Python will create a new object in a memory heap, and execute the __init__() method. The parameter self is similar to the this keyword in Java. In Python, when you create a new instance with Person() in Line 7, what really happens in the background is that a new object is created and assigned to self. To make it more concrete, below is (most likely) what goes on in the background. Please DO NOT write such code – this is just for illustrative purposes!! # new object of type Person created in heap, and assigned to the variable self self = object.__new__(Person)
# The __init__() method for class Person is invoked Person.__init__(self, "Josiah", "Wang", 20)
return self
So self is a reference to the new Person instance that Python has just allocated in heap memory. << Previous Next >> Page designed by Josiah Wang Department of Computing | Imperial College London