Python Classes and OOP
Python is an object-oriented programming language. Almost everything in Python is an object, with its own properties and methods.
Creating a Class
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
The __init__() Function
All classes have a function called __init__(), which is always executed when the class is being initiated. Use it to assign values to object properties.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
The self Parameter
The self parameter is a reference to the current instance of the class, and is used to access variables that belong 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.
Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.
# Parent Class
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Child Class
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
x.printname()