OOP in Python: Classes
- Python is an object oriented programming language.
- Almost everything in Python is an object, with its properties and methods.
- A Class is like an object constructor, or a “blueprint” for creating objects.
Create a Class:
To create a class, use the keyword class:
class Person:
pass
# class definitions cannot be empty
# put in the pass statement to avoid getting an error in case you need to define class objects later
The __init__() Function:
To understand the meaning of classes we have to understand the built-in __init__() function.
- All classes have a function called __init__(), which is always executed when the class is being initiated.
- Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created.
-
Note: The __init__() function is called automatically every time the class is being used to create a new object.
class Person:
def __init__(self, name, surname, age, email):
self.name = name
self.surname = surname
self.age = age
self.email = email
p1 = Person('Chucknorris', 'Madamombe', 35, '[email protected]')
print(p1.name)
print(p1.surname)
print(p1.age)
print(p1.email)
Object Methods
- Objects can also contain methods. Methods in objects are functions that belong to the object
- A function defined inside a class is called a method
- Let us create a method in the Person class
- Insert a function that prints a greeting, and execute it on the p1 object:
class Greetings:
def __init__(self, name, surname, age): # All classes must have an __init__ function defined.
self.name = name
self.surname = surname
self.age = age
def introduce(self): # Method is a function defined inside the class
welcome_message = print('My name is ' + self.name + ' ' + self.surname + '.' + ' I am now ' + str(self.age) + ' years old.')
return welcome_message
p1 = Greetings('Chucknorris', 'Madamombe', 35)
p1.introduce()
The self Parameter
- The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
- It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class.
Get full code from my GitHub repo.