In Object-Oriented Programming (OOP), a class is a structure that defines a type of object by describing its properties (attributes) and behaviors (methods). It serves as a template or blueprint for creating objects.
What is a Class?
A class in Python allows you to define:
-
✅ Attributes — characteristics of the object (e.g., name, age, color)
-
✅ Methods — actions the object can perform (e.g., speak, eat, sleep)
When a class is defined, no object exists yet. You must instantiate it to create a usable object in memory. Each object (or instance) will have its own values for the attributes and can execute the methods defined in the class.
How to Create a Class in Python
You use the class
keyword followed by the name of the class. Inside the class, methods and attributes are defined using indentation.
Here’s a simple example:
class Person:
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.")
Explanation:
-
__init__
is the constructor method, automatically called when a new object is created. -
self
refers to the current instance of the class. -
introduce()
is a method that prints a personal introduction.
Example: Class Cat
Here’s a more complete example using a class to define a cat:
class Cat:
def __init__(self, name, color, age):
self.name = name
self.color = color
self.age = age
self.health = "good" # default attribute
self.hunger = "satisfied" # default attribute
def meow(self):
print(f"{self.name} is meowing...")
def eat(self):
self.hunger = "full"
print(f"{self.name} is eating.")
def sleep(self):
print(f"{self.name} is sleeping.")
def check_health(self):
print(f"{self.name}'s health is {self.health}.")
def check_hunger(self):
print(f"{self.name} is {self.hunger}.")
In this example, the Cat
class has these attributes:
-
name
,color
,age
,health
,hunger
And these methods:
-
meow()
,eat()
,sleep()
,check_health()
,check_hunger()
Example usage:
my_cat = Cat("Whiskers", "gray", 3)
my_cat.meow()
my_cat.eat()
my_cat.check_hunger()
With this structure, you can create many cat objects, each with unique characteristics and behaviors.
Copyright Statement: Unless stated otherwise, all articles are original to this site, please credit the source when sharing.
Article link:http://pybeginners.com/object-oriented-programming/object-oriented-programming-what-is-a-class-and-how-to-create-a-class-in-python/
License Agreement:Attribution-NonCommercial 4.0 International License