Python is an object-oriented programming (OOP) 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.
1. Create class & object
To create a class, use the keyword class.
class MyClass:
x = 5
# Create an Object
p1 = MyClass()
print(p1.x) # 5
2. The __init__() constructor and self
The examples above are classes and objects in their simplest form. 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 (constructor). It is used to assign values to object properties.
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, but it has to be the first parameter of any function in the class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name) # John
print(p1.age) # 36
3. Instance vs Class Variables
- Instance Variables: Variables defined inside
__init__(prefixed withself). They are unique to each instance. - Class Variables: Variables defined directly inside the class, outside any methods. They are shared across all instances.
class Dog:
species = "Canis familiaris" # Class Variable (shared)
def __init__(self, name):
self.name = name # Instance Variable (unique)
dog1 = Dog("Buddy")
dog2 = Dog("Miles")
print(dog1.species) # Canis familiaris
print(dog2.name) # Miles
4. Methods (Instance, Class, Static)
Objects can also contain methods. Methods in objects are functions that belong to the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Class Methods and Static Methods
@classmethod: Takesclsas the first argument instead ofself. Works on class variables.@staticmethod: Takes neitherselfnorcls. Behaves like a plain function that just happens to live in the class namespace.
class MathUtils:
@staticmethod
def add(x, y):
return x + y
print(MathUtils.add(5, 10)) # 15
5. Inheritance (Single, Multiple, Multilevel)
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.
# Parent
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Child
class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname()
6. super() function and Method Overriding
When a child class has a method with the same name as the parent class, it overrides the parent’s method. To call the parent’s method from inside the child, we use super().
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname) # Calls parent constructor
self.graduationyear = year
# Overriding the parent method
def printname(self):
print(f"Student: {self.firstname} {self.lastname}, Grad: {self.graduationyear}")
7. Encapsulation
Encapsulation is the bundling of data and methods that act on that data. In Python, we use naming conventions to indicate private variables.
_variable: Protected variable (should not be accessed directly outside the class).__variable: Private variable (name mangled by Python to make it harder to access).
class Account:
def __init__(self):
self.__balance = 0 # Private
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
8. Polymorphism
Polymorphism means “many forms”. It allows methods in different classes to have the same name. Python relies on Duck Typing.
class Car:
def move(self): print("Drive!")
class Boat:
def move(self): print("Sail!")
for x in (Car(), Boat()):
x.move() # Polymorphism in action
9. Property decorators (@property)
The @property decorator allows you to define methods that can be accessed like attributes. This is used for getter and setter logic.
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return (self._celsius * 1.8) + 32
t = Temperature(25)
print(t.fahrenheit) # 77.0 (Accessed like an attribute, not a method call)
Discussion
Loading comments...