Back to Python
2026-03-158 min read

Swift OOP (Python Programming)

Learn Swift OOP (Python Programming) step by step with clear examples and exercises.

Title: Mastering Swift Object-Oriented Programming (Python) - Expanded Lesson

Why This Matters

Swift Object-Oriented Programming (OOP) is a fundamental concept that empowers developers to create reusable, modular, and scalable code. It's essential for building complex applications with maintainable and efficient codebases. Understanding Swift OOP will help you excel in coding interviews, solve real-world programming challenges, and write more robust software.

Benefits of Swift OOP

  1. Encapsulation: Hiding implementation details from the user, promoting modularity and reducing complexity.
  2. Inheritance: Reusing existing code by creating new classes that inherit properties and methods from a parent class.
  3. Polymorphism: Treating objects of different types as if they were of the same type, providing greater flexibility in designing applications.
  4. Modularity: Organizing code into smaller, manageable units for easier maintenance and reuse.
  5. Code Reusability: Encouraging the creation of classes that can be used across multiple projects or applications.

Prerequisites

Before diving into Swift OOP, make sure you have a solid understanding of the following topics:

  1. Python syntax and data structures (variables, functions, loops, conditionals)
  2. Basic object-oriented programming principles (classes, objects, inheritance, polymorphism)
  3. Familiarity with Swift programming language (optional but recommended for better understanding)
  4. Understanding of Python's class structure and inheritance hierarchy
  5. Knowledge of Python's special methods like __init__, __str__, and __repr__
  6. Comfortable working in a Python environment (IDE or Jupyter notebook)
  7. Familiarity with object-oriented design patterns, such as the Factory pattern, Singleton pattern, and Decorator pattern.

Core Concept

In Python, we use classes to define new types of objects and encapsulate data and behavior. Here's a detailed example of how to create a class in Python:

class MyClass:

Class variables (shared by all instances)

class_variable = "This is a class variable"

def __init__(self, instance_variable):

Constructor method that initializes instance variables

self.instance_variable = instance_variable

def my_method(self):

Instance methods can access both class and instance variables

print(f"Instance variable: {self.instance_variable}")

print(f"Class variable: {MyClass.class_variable}")

def __str__(self):

Special method to define how the object is represented as a string

return f"MyClass({self.instance_variable})"


In this example, `MyClass` is a user-defined class with an instance variable (`instance_variable`) and a class variable (`class_variable`). The `__init__` method serves as the constructor for creating new instances of the class. The `my_method` is an instance method that demonstrates how to access both class and instance variables. Additionally, we have defined a special method `__str__` which returns a string representation of the object.

### Understanding Class Variables and Instance Variables

Class variables are shared by all instances of a class, while instance variables belong to each individual object created from the class. It's important to understand how these variables behave when accessed within methods or directly:

class MyClass:

class_variable = "This is a class variable"

def __init__(self, instance_variable):

self.instance_variable = instance_variable

def my_method(self):

print(f"Instance variable: {self.instance_variable}")

print(f"Class variable: {MyClass.class_variable}")

my_object1 = MyClass("Object 1")

my_object2 = MyClass("Object 2")

print(f"MyObject1 instance variable: {my_object1.instance_variable}")

print(f"MyObject1 class variable: {MyClass.class_variable}")

print(f"MyObject2 instance variable: {my_object2.instance_variable}")

print(f"MyObject2 class variable: {MyClass.class_variable}")


In this example, we create two instances of the `MyClass`. When accessing the variables directly on each instance and on the class itself, you'll notice that the class variable has the same value for both objects since it is shared by all instances:

MyObject1 instance variable: Object 1

MyObject1 class variable: This is a class variable

MyObject2 instance variable: Object 2

MyObject2 class variable: This is a class variable

Worked Example

Let's create a simple example using Swift OOP in Python:

class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year

def display_info(self):
print(f"Brand: {self.brand}")
print(f"Model: {self.model}")
print(f"Year: {self.year}")

def calculate_value(self):
current_year = datetime.datetime.now().year
depreciation_rate = 0.10
value = self.original_price * (1 - depreciation_rate * (current_year - self.year))
return value

def __str__(self):
return f"Car({self.brand}, {self.model}, {self.year})"

@classmethod
def get_default_car(cls):
"""
Returns a default car instance with specific values for brand, model, and year.
"""
return cls("Toyota", "Camry", 2021)

my_car = Car("Toyota", "Corolla", 2021)
my_car.original_price = 30000
my_car.display_info()
print(f"Current value: ${my_car.calculate_value():.2f}")

default_car = Car.get_default_car()
default_car.display_info()

In this example, we define a Car class with three instance attributes (brand, model, and year). The constructor initializes these attributes when creating a new car object. We also create methods called display_info that prints the information about the car and calculate_value that calculates the car's current value based on its year and a depreciation rate. Additionally, we have defined a class method called get_default_car, which returns a default instance of the Car class with specific values for brand, model, and year.

Understanding Class Methods (ClassMethods)

Class methods, also known as static methods in some languages, are methods that can be called on the class itself rather than an individual instance. In Python, we define class methods using the @classmethod decorator:

@classmethod
def get_default_car(cls):
"""
Returns a default car instance with specific values for brand, model, and year.
"""
return cls("Toyota", "Camry", 2021)

In the example above, get_default_car is a class method that can be called directly on the Car class:

default_car = Car.get_default_car()
default_car.display_info()

Common Mistakes

  1. Forgetting to initialize instance attributes in the constructor (__init__ method)
  2. Accessing class attributes as if they were instance attributes (e.g., using MyClass.attribute instead of self.attribute)
  3. Creating methods without proper indentation or syntax errors
  4. Misunderstanding inheritance and overriding methods in Python
  5. Not properly defining the constructor when subclassing
  6. Forgetting to define special methods like __str__ and __repr__ for custom object representations
  7. Incorrectly using the super() function during method calls or inheritance
  8. Overlooking the importance of encapsulation and data hiding in OOP
  9. Failing to use class methods when appropriate
  10. Neglecting to document classes, methods, and variables with clear comments and docstrings

Subheadings under Common Mistakes:

  • Misusing Class Attributes
  • Forgetting to Define Special Methods
  • Incorrect Use of Superclass Methods
  • Ignoring Encapsulation Principles
  • Overlooking the Importance of Class Methods
  • Neglecting Proper Documentation

Practice Questions

  1. Create a class called Person with instance attributes for name, age, and occupation. Include a method to display this information and another method to calculate the person's retirement age (assuming retirement at 65).
  2. Modify the Car class from the worked example to include a method that calculates the car's fuel efficiency based on its year (e.g., more efficient for newer cars).
  3. Create a class called Rectangle with instance attributes for width and height, and methods to calculate the area and perimeter. Also, create a subclass called Square that inherits from Rectangle, and overrides the method to calculate the area when all sides are equal (i.e., square).
  4. Write a class called Student that includes instance attributes for name, age, and GPA. Include a method to display this information and another method to calculate the student's cumulative GPA (average of all grades). Also, create a subclass called GraduateStudent that inherits from Student, and overrides the method to calculate the cumulative GPA by excluding any grades below a certain threshold (e.g., C-).
  5. Implement the Factory pattern in Python by creating a class called ShapeFactory with static methods to create instances of different shape classes like Circle, Rectangle, and Square.
  6. Create a singleton pattern for a logging utility class that logs messages to a file or console, ensuring only one instance of the class exists during runtime.
  7. Implement a decorator in Python that logs method calls on a class with their arguments and return values.

FAQ

Q: What is the purpose of the constructor in Python?

A: The constructor (__init__ method) initializes instance attributes when creating a new object of a class and can also perform other setup tasks.

Q: How can I access class attributes in an instance method?

A: You can access class attributes using the MyClass.attribute syntax within an instance method. However, it's generally recommended to use self for instance attributes and class variables like MyClass.class_variable.

Q: What is inheritance, and how does it work in Python?

A: Inheritance allows one class to acquire properties (methods and attributes) from another class. In Python, we use the super() function to call parent class methods from a subclass.

Q: How do I override a method in Python?

A: To override a method in a subclass, you simply define the same method with the desired behavior. The subclass's implementation will take precedence over the superclass's implementation.

Q: What is polymorphism, and how does it work in Python?

A: Polymorphism allows objects of different classes to be treated as if they were of the same class. In Python, this is achieved through method overriding and dynamic binding at runtime.

Q: What is encapsulation, and why is it important in OOP?

A: Encapsulation refers to hiding the implementation details of an object and exposing only the necessary interfaces. It helps maintain code modularity, reduces complexity, and improves code reusability.

Q: How do I define special methods like __str__ and __repr__ in Python?

A: Special methods are defined using double underscores before and after their names (e.g., __str__, __repr__). These methods should return a string representation of the object, with __str__ being used for human-friendly output and __repr__ for programmatic use.

Q: What is the difference between __str__ and __repr__ in Python?

A: __str__ returns a user-friendly string representation of an object, while __repr__ returns a more verbose, developer-friendly string that can be used to recreate the object.

Q: What is the purpose of class methods (classmethods) in Python?

A: Class methods are used when you want to perform operations on the class itself rather than an instance of the class. They are defined using the @classmethod decorator and can be called directly on the class without creating an instance.

Q: What is the purpose of static methods in Python?

A: Static methods are similar to class methods but do not have access to the class's attributes or methods, including the constructor. They are defined using the @staticmethod decor

Swift OOP (Python Programming) | Python | XQA Learn