Defining a class
Hopefully I’ve sold you into OOP!
Now, let’s start by designing the main component of OOP, which is a class.
Like mentioned in the video, a class is a blueprint or outline for an instance of an object that you will create. Sort of like a plan for building a house.
This is how you define a class in Python (let’s try to create the class Person as an example)
class Person:
pass
Quite straighforward!
PEP 8 states that class names should normally use the CapWords convention. So name your objects in CamelCase, like YorkshireTerrier
or ComputerMonitor
. This is actually the convention in most programming languages.
You can now create a new instance of your brand new Person
class (although it is not quite useful at the moment)
person = Person()
print(type(person))
Class constructor
Now the Person
class already has a default constructor that creates a new instance of a class (the constructor is called when you say Person()
).
To create your own custom constructor, we use a special Python built-in method called __init__()
. The double underscores on both side is a Python convention that indicates that this is a “special” Python function that does special things (we will see more later).
class Person:
def __init__(self):
print("I created a person! It's alive!")
person = Person()
__init__(self)
will be the first method called when you construct your object instance with Person()
.
Running the script above will print out I created a person! It's alive!
. That proves __init__()
has been executed.
Note the variable self
in the parameter of the constructor. It refers to the instance of the class (i.e. object) that you just created.
Do not worry for now, it will make more sense later. Just remember that you must add self as the first parameter of __init__()
. While you are allowed to use other variable names, I recommend you stick to self
because it is the standard.
If you have programmed in C++ or Java, self
is essentially this
.