Course

Python Class: Syntax and Examples [Python Tutorial]

In Python, classes bundle data and functionality within templates you can use to create objects from.

How to Use Python Classes

Classes are a fundamental component of object-oriented programming (OOP). With classes, you can turn complex systems into objects using data structures like dictionaries, lists, and tuples.

Python’s class syntax is easy to learn for beginners and similar to that of other programming languages (e.g., Java). Here’s a brief intro:

Python Creating a Class

To create a class in Python code, use the class keyword followed by the class name and a colon.

Classes often include an __init__() method, also called a constructor. __init__(), which has two underscores as prefixes and suffixes, is a special method to initialize (or set initial values for) class attributes. These are known as instance attributes, as they are specific to each instance of the class.

python
class MyClass: def __init__(self, attribute1, attribute2): self.attribute1 = attribute1 self.attribute2 = attribute2
  • class: The keyword to start a class definition in Python.
  • MyClass: The name of the class, typically with every word in capitals, including the first word.
  • __init__: The constructor (or init) method to set default values for the new instance.
  • self:  A parameter to reference the new instance.
  • attribute1, attribute2: Attributes of the class, often referred to as instance variables.

The attribute name is used to assign unique properties to each instance. Each class can define multiple instance attributes, allowing for flexible object creation.

Python Creating an Instance of a Class

To create a new Python object from a class, call the class like a function, passing any required arguments to the constructor. This instantiation process allows you to create multiple objects from the same class, each with its own unique set of data, defined by their instance attributes.

python
my_object = MyClass("value1", "value2")
  • MyClass: The name of the class you want to use as a template for the new object.
  • my_object: The variable name for the new instance of the class.

Creating Class Methods

Class methods define a class’s behavior and allow instances of a class to perform specific actions. You can define class methods using the def keyword inside the class body and use them to operate on instance data or perform tasks.

python
class MyClass: def __init__(self, attribute1, attribute2): self.attribute1 = attribute1 self.attribute2 = attribute2 def my_method(self): return f"Attributes are: {self.attribute1} and {self.attribute2}" # Creating an instance and calling a class method my_object = MyClass("value1", "value2") print(my_object.display_attributes()) # Outputs: 'Attributes are: value1 and value2'

Calling Class Methods

In Python, methods can operate on instance data or perform specific tasks. You can call methods from a class to perform actions or retrieve data. To call a method, you use the syntax my_object.my_method(), which accesses the method from the class instance.

python
class Greeting: def __init__(self, name): self.name = name def say_hello(self): return f"Hello, {self.name}!" # Creating an instance greet = Greeting("Alice") # Calling an instance method message = greet.say_hello() print(message) # Outputs: 'Hello, Alice!'

When to Use Classes in Python

Classes in Python programming help you group behavior and data. They provide a structured way to define and organize the properties and behaviors that different objects should have.

Encapsulation of Data and Methods

You can use classes to group related data and methods. This makes your code easier to manage and helps prevent accidental changes. For example, encapsulation helps you hide the implementation details of algorithms and limit access to class attributes.

python
class Book: def __init__(self, title, author, is_available=True): self.title = title self.author = author self.is_available = is_available def display_info(self): return f"{self.title} by {self.author}" def check_availability(self): return self.is_available book = Book("1984", "George Orwell", is_available=False) print(book.check_availability()) # Outputs: False

Modeling the Real World

You can use classes to resemble the natural world in your application. This approach is beneficial for applications that simulate real-world systems, such as inventory management or customer tracking. Creating a class for each entity ensures that your application accurately represents and manages these entities.

python
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def car_details(self): return f"{self.year} {self.make} {self.model}"

Inheritance for Code Reuse

You can also create new classes to extend existing classes, reusing code and reducing unnecessary repetition. Inheritance helps you build a hierarchy of classes that share some functionality while allowing for specialized behavior in subclasses. Using inheritance, the derived class (e.g., ElectricCar) inherits attributes and methods from a parent class (e.g., Car).

python
class ElectricCar(Car): def __init__(self, make, model, year, battery_size): super().__init__(make, model, year) self.battery_size = battery_size def battery_info(self): return f"Battery size: {self.battery_size} kWh"

A parent class is sometimes also referred to as a base class. Both terms describe the same concept - a class that passes down its functionality to another class through inheritance.

Python Class Examples

Customer Database Application

A customer database application might use classes to handle customer records. Each customer can have a name, email address, and purchase history (stored as a dict). Class methods like add_purchase() can update a customer’s purchase history by working with instance attributes.

python
class Customer: def __init__(self, customer_id, name, email): self.customer_id = customer_id self.name = name self.email = email self.purchase_history = [] def update_email(self, new_email): self.email = new_email def add_purchase(self, item, amount): self.purchase_history.append({'item': item, 'amount': amount}) def get_purchase_history(self): return self.purchase_history customer1 = Customer(1, "Alice", "alice@example.com") customer1.update_email("alice.new@example.com") customer1.add_purchase("Laptop", 1200) print(customer1.get_purchase_history()) # Outputs: [{'item': 'Laptop', 'amount': 1200}]

Here, customer_id, name, and email are examples of instance attributes used to store individual customer details.

Inventory Management System

An inventory management system might use classes to represent items in stock. Each item can be an instance of an InventoryItem class, with methods to work on item data.

python
class InventoryItem: def __init__(self, item_id, name, quantity): self.item_id = item_id self.name = name self.quantity = quantity def update_quantity(self, new_quantity): self.quantity = new_quantity def item_details(self): return f"ID: {self.item_id}, Name: {self.name}, Quantity: {self.quantity}" item1 = InventoryItem(101, "Laptop", 50) item1.update_quantity(45) print(item1.item_details()) # Outputs: 'ID: 101, Name: Laptop, Quantity: 45'

Game Characters

Games might define the properties and actions of characters within classes. Using classes, game programmers can create multiple characters with shared behaviors and attributes while still allowing for unique characteristics.

python
class Character: def __init__(self, name, health, attack_power): self.name = name self.health = health self.attack_power = attack_power def attack(self): return f"{self.name} attacks with power {self.attack_power}" hero = Character("Warrior", 100, 75) print(hero.attack()) # Outputs: 'Warrior attacks with power 75'

E-commerce Platform

An e-commerce platform might use classes to handle orders. Each order can be an instance of an Order class. Python class methods can add items, calculate the total price, and retrieve order details.

python
class Order: def __init__(self, order_id, customer): self.order_id = order_id self.customer = customer self.items = [] def add_item(self, item_name, price, quantity): self.items.append({'item_name': item_name, 'price': price, 'quantity': quantity}) def total_price(self): return sum(item['price'] * item['quantity'] for item in self.items) def order_details(self): return {'order_id': self.order_id, 'customer': self.customer, 'items': self.items, 'total': self.total_price()} order1 = Order(1, "Alice") order1.add_item("Laptop", 1200, 1) order1.add_item("Mouse", 25, 2) print(order1.order_details()) # Outputs order details with total price

Learn More About Python Classes

Python Class Variables and Instance Variables

In Python, class variables are helpful for attributes that are the same for all instances of that class. On the other hand, instance variables represent data of any data type that varies between instances.

python
class Teacher: school_name = "Green Valley High" def __init__(self, name): self.name = name teacher1 = Teacher("Mrs. Smith") teacher2 = Teacher("Mr. Johnson") print(Teacher.school_name) # Outputs: 'Green Valley High' print(teacher1.name) # Outputs: 'Mrs. Smith'

Instance attributes are sometimes also referred to as instance variables. Both terms describe the same concept: data that belongs to a specific object created from a class.

Python Class Inheritance and Subclassing

Inheritance allows you to create a new class based on an existing class. This helps create a logical class hierarchy and reuse common behavior.

python
class Human: def speak(self): return "Speaking..." class Child(Human): def play(self): return "Playing..." child = Child() print(child.speak()) # Outputs: 'Speaking...' print(child.play()) # Outputs: 'Playing...'

Python Abstract Classes

Abstract classes in Python provide a way to define a common interface (or API) for a group of related classes. However, abstract classes only serve as templates for other classes, so you can’t create instances of them.

To define an abstract class, import the built-in abc module and make your class inherit from ABC.

python
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def sound(self): pass class Dog(Animal): def sound(self): return "Bark" class Cat(Animal): def sound(self): return "Meow" dog = Dog() cat = Cat() print(dog.sound()) # Outputs: 'Bark' print(cat.sound()) # Outputs: 'Meow'

Python Data Classes

Python 3 allows you to define classes as data classes and automatically generate methods like __init__, __repr__, and __eq__. Data classes are particularly useful for representing data structures such as configurations or database rows.

python
from dataclasses import dataclass @dataclass class Employee: name: str age: int role: str employee1 = Employee(name="Alice", age=30, role="Engineer") print(employee1) # Outputs: Employee(name='Alice', age=30, role='Engineer')

Python Enum Classes

Enum classes define a set of named values, reducing the possibility of invalid values. Enums are useful for representing fixed sets of related constants, such as days of the week or status codes for debugging.

python
from enum import Enum class Status(Enum): NEW = 1 IN_PROGRESS = 2 COMPLETED = 3 print(Status.NEW) # Outputs: 'Status.NEW'

Class Decorators and Properties

You can use class decorators and properties to enhance class functionality. Decorators can modify class behavior. Properties provide a way to define methods you can access, such as attributes.

python
class Student: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name @property def full_name(self): return f"{self.first_name} {self.last_name}" student1 = Student("John", "Doe") print(student1.full_name) # Outputs: 'John Doe'

Custom Iterators in Python Classes

Custom iterators let you control how iteration over class objects works. To create a customer iterator, implement __iter__() (returning the iterator object) and __next__() (defining the next value and raising StopIteration when done).

python
class CustomIterator: def __init__(self, items): self.items = items self.index = 0 def __iter__(self): return self def __next__(self): if self.index < len(self.items): value = self.items[self.index] self.index += 1 return value raise StopIteration # Example usage fruits = CustomIterator(['apple', 'banana', 'cherry']) for fruit in fruits: print(fruit) # Outputs: apple, banana, cherry