Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that organizes data and behavior into objects. In Python, everything is an object, including variables, functions, and classes.
Classes and Objects
A class is a blueprint for creating objects. It defines the properties and behavior that the objects belonging to the class will have. Properties are represented by variables called attributes, and behavior is represented by functions called methods.
To create an object from a class, we use the constructor method called __init__()
. The constructor initializes the object with the specified values for its attributes.
Let's take a look at an example:
PYTHON
1# Define a Player class
2
3class Player:
4 def __init__(self, name, age):
5 self.name = name
6 self.age = age
7
8 def introduce(self):
9 print(f"Hi, my name is {self.name} and I am {self.age} years old.")
10
11# Create an object of the Player class
12
13player1 = Player("John", 25)
14
15# Call the introduce() method
16
17player1.introduce() # Output: Hi, my name is John and I am 25 years old.
xxxxxxxxxx
10
class Player:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hi, my name is {self.name} and I am {self.age} years old.")
player1 = Player("John", 25)
player1.introduce()
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment