OOP in Python3
Object-oriented programming (OOP) is a programming paradigm that allows developers to organize and structure their code in a way that represents real-world objects and their interactions. In this tutorial, we will show you how to use OOP in Python3.
A class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).
First, let’s create a simple class called Person
:
class Person:
pass
This class doesn’t have any attributes or methods yet, but it’s a starting point. We can create an instance of the class by calling the class name as a function:
p = Person()
We can give our class a __init__
method, which is a special method that gets called when an object is created. The __init__
method is used to initialize the state of the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Now, when we create an instance of the Person
class, we need to provide values for the name
and age
attributes:
p = Person("John", 30)
We can also give our class methods, which are functions that are associated with a class and its objects.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
p = Person("John", 30)
p.say_hello()
This will print “Hello, my name is John and I am 30 years old.”
We can also define class variables, which are variables that are shared among all instances of a class. We define class variables outside of any method, usually at the top level of the class definition.
class Person:
species = "Homo Sapiens"
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
p = Person("John", 30)
print(p.species) # Homo Sapiens
Inheritance is a way to create a new class that is a modified version of an existing class. The new class is called the derived class, and the existing class is called the base class.
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
s = Student("Alice", 20, "123456")
s.say_hello()
print(s.student_id) # 123456
In the above example, the Student
class inherits from the Person
class, and it has an additional attribute called student_id
.