A class is a blueprint or a template for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of that class will have.
Syntax
Python
class ClassName:
# Attributes (class and instance variables)
# Methods (functions defined within the class)
Class Attributes
Class attributes are shared by all instances of a class. They are defined outside any method in the class body.
Python
class Dog:
species = "Canis lupus familiaris" # Class attribute
Instance Attributes
Instance attributes are specific to each object of a class. They are usually defined within the __init__
method (constructor).
Python
class Dog:
def __init__(self, name, breed):
self.name = name # Instance attribute
self.breed = breed # Instance attribute
Methods
Methods are functions defined within a class. They operate on the object’s data.
Python
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} barks!")
The __init__
Method
The __init__
method is a special method called the constructor. It is used to initialize the object’s attributes when an object is created.
Python
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
Example
Python
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def description(self):
print(f"This is a {self.year} {self.make} {self.model}")
# Create objects
car1 = Car("Toyota", "Camry", 2023)
car2 = Car("Honda", "Accord", 2022)
# Access attributes
print(car1.make) # Output: Toyota
print(car2.model) # Output: Accord
# Call methods
car1.description() # Output: This is a 2023 Toyota Camry
By understanding these components, you can create well-structured and reusable classes in your Python programs.
Defining Classes
What is the __init__
method?
The __init__
method is the constructor of a class, used to initialize object attributes.
How do I define a class?
Use the class
keyword followed by the class name and a colon.
What is the difference between class and instance attributes?
Class attributes are shared by all instances of a class, while instance attributes are specific to each object.
Where are class attributes defined?
Class attributes are defined outside any method in the class body.
Where are instance attributes defined?
Instance attributes are typically defined within the __init__
method.
What is a method in a class?
A method is a function defined within a class. It operates on the object’s data.
What is the self
parameter?
self
refers to the instance of the class and is used to access instance attributes and methods.
Should I use class attributes frequently?
Use class attributes sparingly, as they can lead to unexpected behavior.
How do I define a method?
Define a function within the class body, with self
as the first parameter.