This is an archived version of the course. Please see the latest version of the course.

Objects in Python

As I have just mentioned, everything is an object in Python.

Naturally, you can define your own classes. In Python 3, all classes inherit the object class by default.

1
2
3
4
class Person:
    pass

person = Person()

Line 2: pass is a special statement in Python that basically says “do nothing”. Useful when you need to put something in an otherwise empty indented block.

Line 4: This creates an instance of Person (i.e. calling the constructor), and assigns the instance to the variable person.

This is equivalent to the following in Java.

1
2
3
4
5
6
// Java equivalent
class Person {
    public static void main(String[] args) {
        Person person = new Person();
    }
}

I will discuss more about Object-Oriented Programming in Python later on. This page is just to ensure that you are clear about the syntax differences between Java and Python for object constructors. We will be talking about objects a lot throughout this tutorial.

Again – I cannot stress this enough – remember that in Python, a variable does not have a type. It is what the variable is pointing to that has a type! This is key to understanding how to “think” of variables in Python compared to in Java. Just have the diagrams from the previous page constantly in your mind as we go along!