how do I program OOP in python
- User
how do I program OOP in python
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
how do I program OOP in python
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Object-Oriented Programming (OOP) in Python revolves around creating classes and objects. Here are the key concepts with examples:
A class is a blueprint for creating objects. Objects are instances of classes.
class Dog:
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age
def bark(self): # Instance method
return f"{self.name} says woof!"
def info(self):
return f"{self.name} is {self.age} years old"
# Creating objects
my_dog = Dog("Buddy", 5)
another_dog = Dog("Max", 3)
print(my_dog.bark()) # Buddy says woof!
print(another_dog.info()) # Max is 3 years old
Encapsulation involves bundling data and methods within a class and controlling access to them.
class BankAccount:
def __init__(self, balance):
self._balance = balance # Protected attribute (convention)
self.__pin = 1234 # Private attribute (name mangling)
def deposit(self, amount):
if amount > 0:
self._balance += amount
def get_balance(self):
return self._balance
@property
def balance(self): # Property decorator for getter
return self._balance
@balance.setter
def balance(self, amount): # Property setter
if amount >= 0:
self._balance = amount
account = BankAccount(1000)
account.deposit(500)
print(account.balance) # 1500
Inheritance allows a class to inherit attributes and methods from another class.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
def move(self):
return f"{self.name} is moving"
class Dog(Animal): # Dog inherits from Animal
def __init__(self, name, breed):
super().__init__(name) # Call parent constructor
self.breed = breed
def speak(self): # Override parent method
return f"{self.name} barks"
class Cat(Animal):
def speak(self):
return f"{self.name} meows"
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers")
print(dog.speak()) # Buddy barks
print(dog.move()) # Buddy is moving (inherited)
Polymorphism allows different classes to be treated through the same interface.
class Shape:
def area(self):
raise NotImplementedError
def perimeter(self):
raise NotImplementedError
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
def perimeter(self):
return 2 * 3.14159 * self.radius
# Polymorphic behavior
shapes = [Rectangle(5, 10), Circle(7)]
for shape in shapes:
print(f"Area: {shape.area()}") # Same method, different implementations
Abstraction hides complex implementation details and shows only essential features.
from abc import ABC, abstractmethod
class Vehicle(ABC): # Abstract base class
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle):
def start(self):
return "Car engine started"
def stop(self):
return "Car engine stopped"
# vehicle = Vehicle() # This would raise an error
car = Car() # Concrete implementation
print(car.start())
class MyClass:
class_variable = 0
def __init__(self, value):
self.instance_variable = value
@classmethod
def from_string(cls, string_value): # Alternative constructor
return cls(int(string_value))
@staticmethod
def utility_function(x, y): # Doesn't access class or instance
return x + y
obj = MyClass.from_string("42")
print(MyClass.utility_function(5, 3)) # 8
class Flyable:
def fly(self):
return "Flying"
class Swimmable:
def swim(self):
return "Swimming"
class Duck(Flyable, Swimmable):
def quack(self):
return "Quack"
duck = Duck()
print(duck.fly()) # Flying
print(duck.swim()) # Swimming
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
p1 = Point(2, 3)
p2 = Point(4, 5)
p3 = p1 + p2 # Uses __add__
print(p3) # Point(6, 8)
This should give you a solid foundation for OOP in Python. Start with simple classes and gradually incorporate more advanced features as you become comfortable with the basics.