📚

Introduction to Object Oriented Programming

Oct 6, 2024

Object Oriented Programming in Python

Introduction

  • Geared towards beginners with some Python knowledge.
  • Focus on creating custom objects using classes.
  • Recommended for those who haven't worked with object-oriented programming (OOP) before.

Understanding Objects

  • Objects are instances of classes.
  • Python uses objects frequently, even if not apparent.
  • Use type() function to see that data types like str and int are classes.

Example:

print(type("Hello")) # Output: <class 'str'> print(type(1)) # Output: <class 'int'>
  • Assigning x = 1 creates an object of class int with value 1.

Methods

  • Methods are functions defined within a class that can operate on objects.
  • Use dot notation to call methods (e.g., string.upper()).
  • Methods are tied to the object's class type.

Example:

string = "hello" print(string.upper()) # HELLO

Creating Custom Classes

  • Define with class keyword, e.g., class Dog:.
  • Can include methods like bark() within the class.

Example:

class Dog: def bark(self): print("bark") # Create instance of Dog my_dog = Dog() my_dog.bark() # Output: bark

The __init__ Method

  • Special method for defining object attributes at instantiation.
  • Uses self to refer to the instance itself.

Example:

class Dog: def __init__(self, name): self.name = name my_dog = Dog("Rex") print(my_dog.name) # Output: Rex

Attributes

  • Attributes are variables associated with objects.
  • Defined often in __init__ using self.
  • Can be accessed or modified via methods or directly.

Example with Methods and Attributes

class Dog: def __init__(self, name, age): self.name = name self.age = age

Inheritance

  • Allows a class to inherit attributes and methods from another class.
  • Use with parent class in parentheses.

Example:

class Animal: def __init__(self, name): self.name = name class Dog(Animal): def bark(self): print("bark")
  • Overriding Methods: Child class can override methods from the parent class.

Example with Overriding:

class Animal: def speak(self): print("I don't know what to say") class Dog(Animal): def speak(self): print("bark")

Static and Class Methods

  • Static Methods: Do not act on instance or class; no self or cls.
  • Class Methods: Act on the class itself; use cls.

Defining Static Method:

class Math: @staticmethod def add(x, y): return x + y print(Math.add(5, 3)) # Output: 8

Defining Class Method:

class Person: number_of_people = 0 @classmethod def people_count(cls): return cls.number_of_people

Recap

  • Python's OOP involves creating classes and instances (objects).
  • Classes define blueprint for objects, including attributes and methods.
  • Inheritance and method types (static, class) enrich class functionality.