Python tutorials > Object-Oriented Programming (OOP) > Classes and Objects > How to define classes (`class`)?
How to define classes (`class`)?
class
keyword. Classes are the foundation of object-oriented programming, allowing you to create blueprints for objects with specific attributes and methods. Understanding how to define classes is crucial for writing modular, reusable, and well-structured Python code.
Basic Class Definition
class
keyword is followed by the name of the class (MyClass
in this case). By convention, class names are capitalized. The pass
statement is a placeholder indicating that the class currently has no attributes or methods. It's necessary to include it; otherwise, you'll get a syntax error.
class MyClass:
pass
Adding Attributes (Variables)
species
is a class attribute shared by all Dog
objects. It is defined outside the __init__
method.__init__
method, which is the constructor for the class. The __init__
method is automatically called when a new object of the class is created. The self
parameter refers to the instance of the class being created.
class Dog:
species = 'Canis familiaris' # Class attribute
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
Adding Methods (Functions)
bark
and description
. Like the __init__
method, all methods must have self
as their first parameter. self
refers to the instance of the class that the method is being called on. The bark
method returns a string representing the dog barking, while the description
method returns a string describing the dog's name and age.
class Dog:
species = 'Canis familiaris'
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f'{self.name} says Woof!'
def description(self):
return f'{self.name} is {self.age} years old.'
Creating Objects (Instances)
__init__
method. In this example, we create two Dog
objects: milo
and buddy
. We then access their attributes and call their methods using the dot notation (object.attribute
or object.method()
).
class Dog:
species = 'Canis familiaris'
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f'{self.name} says Woof!'
def description(self):
return f'{self.name} is {self.age} years old.
# Creating instances
milo = Dog('Milo', 3)
buddy = Dog('Buddy', 5)
print(milo.name) # Output: Milo
print(buddy.bark()) # Output: Buddy says Woof!
print(milo.description()) # Output: Milo is 3 years old.
Concepts Behind the Snippet
Real-Life Use Case Section
Lion
, Elephant
, Penguin
). Each class would have attributes like name, age, and species, and methods like eat
, sleep
, and make_sound
. This allows you to model the zoo in a structured and organized way. Similarly, in web development, user profiles, blog posts, and shopping cart items can be modeled as classes.
Best Practices
Interview Tip
__init__
method. You might be asked to design a class to represent a real-world object or concept during a technical interview. Practice explaining the concepts of OOP (abstraction, encapsulation, inheritance, polymorphism) and how they relate to class definitions.
When to Use Classes
Memory Footprint
Alternatives
However, classes offer better organization, encapsulation, and reusability for complex scenarios.
Pros
Cons
FAQ
-
What is the purpose of the `__init__` method?
The__init__
method is the constructor for a class. It is automatically called when a new object of the class is created. Its primary purpose is to initialize the object's attributes with the values passed as arguments. -
What does `self` refer to?
self
refers to the instance of the class that the method is being called on. It allows you to access the object's attributes and call its methods from within the class definition. -
How do I access attributes and methods of an object?
You access attributes and methods of an object using the dot notation (object.attribute
orobject.method()
). For example, if you have an object namedmy_object
with an attribute namedname
and a method namedgreet
, you would access them asmy_object.name
andmy_object.greet()
, respectively.