class
In Python, a class is a blueprint for creating objects, providing initial values for state (attributes) and implementations of behavior (methods or functions). Classes encapsulate data for the object and provide methods for interacting with that data.
You define a class using the class
keyword followed by the class name and a colon. Inside the class, you define methods, including the special method .__init__()
, which initializes new objects.
Classes enable you to implement the principles of object-oriented programming (OOP) like encapsulation, inheritance, and polymorphism, helping you write more organized and reusable code.
Example
Here’s a quick example of defining and using a class in Python:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
return f"{self.name} says woof!"
# Usage
frieda = Dog("Frieda", 5)
# Call the .speak() method
print(frieda.speak()) # Output: Frieda says woof!
# Access attributes
print(f"Name: {frieda.name}") # Output: Name: Frieda
print(f"Age: {frieda.age}") # Output: Age: 5
# Modify attributes
frieda.age += 1
print(
f"{frieda.name} is now {frieda.age} years old."
) # Output: Frieda is now 6 years old.
In this example, Dog
is a class with an initializer method .__init__()
that sets up the .name
and .age
attributes. The .speak()
method returns a string representing the dog’s bark. You create an instance of Dog
by calling Dog()
with appropriate values for each argument to .__init__()
.
Related Resources
Tutorial
Python Classes: The Power of Object-Oriented Programming
In this tutorial, you'll learn how to create and use full-featured classes in your Python code. Classes provide a great way to solve complex programming problems by approaching them through models that represent real-world objects.
For additional information on related topics, take a look at the following resources:
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Python Class Constructors: Control Your Object Instantiation (Tutorial)
- Python's Magic Methods: Leverage Their Power in Your Classes (Tutorial)
- Python's Instance, Class, and Static Methods Demystified (Tutorial)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Using Python Class Constructors (Course)
- Python Class Constructors: Control Your Object Instantiation (Quiz)
- Python's Magic Methods in Classes (Course)
- Python's Magic Methods: Leverage Their Power in Your Classes (Quiz)
- OOP Method Types in Python: @classmethod vs @staticmethod vs Instance Methods (Course)