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 C++.
1
2
3
4
5
6
7
8
// C++ equivalent
class Person {};
int main() {
Person* person = new Person();
delete person;
return 0;
}
Note that Python always creates object instances in the memory heap. So this is different from the static memory allocation version in C++ (Person person;
or Person person();
or Person person = 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 C++ 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 C++. Just have the diagrams from the previous page constantly in your mind as we go along!