Skip to content

Instantly share code, notes, and snippets.

@jonathanhle
Last active October 29, 2023 02:22
Show Gist options
  • Save jonathanhle/d3fa1b2257970a5a11a3c25702ef6c5c to your computer and use it in GitHub Desktop.
Save jonathanhle/d3fa1b2257970a5a11a3c25702ef6c5c to your computer and use it in GitHub Desktop.
Simplified Python OOP Basics

Simplified Python OOP Basics

  1. Class: A blueprint for creating objects (specific instances) with certain properties and methods. It's like a template for building objects.

    class Car:
        pass
  2. Object: An instance of a class. It's like building a car using the Car blueprint.

    my_car = Car()
  3. Attributes: Characteristics or properties of an object. For example, the color or model of a car.

    class Car:
        def __init__(self, color, model):
            self.color = color
            self.model = model
    
    my_car = Car("red", "sedan")
  4. Methods: Functions defined within a class that describe the actions or behaviors of an object.

    class Car:
        def __init__(self, color, model):
            self.color = color
            self.model = model
    
        def start_engine(self):
            print("The engine is running!")
    
    my_car = Car("red", "sedan")
    my_car.start_engine()
  5. Inheritance: The ability of a new class to inherit properties and methods from a parent class.

    class ElectricCar(Car):
        def __init__(self, color, model, battery_capacity):
            super().__init__(color, model)
            self.battery_capacity = battery_capacity
    
    my_electric_car = ElectricCar("blue", "hatchback", 100)
  6. Encapsulation: Restricting direct access to an object's attributes and methods, and instead using public methods to interact with them. There are two main ways to achieve encapsulation in Python:

    • Using a single underscore (_): This is a convention to indicate that a variable or method is intended for internal use only. It's not enforced by the language, but other developers should treat it as a non-public part of the class.

    • Using double underscores (__): This enforces name mangling, which means that the attribute or method will be changed to a harder-to-access name, making it more difficult (but not impossible) to accidentally access or modify it from outside the class.

    class Car:
        def __init__(self, color, model):
            self._color = color
            self._model = model
    
        def get_color(self):
            return self._color
    
        def set_color(self, color):
            self._color = color
    
    my_car = Car("red", "sedan")
    my_car.set_color("blue")
    print(my_car.get_color())
  7. Polymorphism: The ability of a class to take on multiple forms. In Python, polymorphism is often achieved through method overriding. This means that a subclass can provide a different implementation for a method that is already defined in its parent class. When you call that method on an object, Python will automatically use the correct implementation based on the object's class.

    class Car:
        def start_engine(self):
            print("The engine is running!")
    
    class ElectricCar(Car):
        def start_engine(self):
            print("The electric engine is running silently!")
    
    my_car = Car()
    my_electric_car = ElectricCar()
    
    my_car.start_engine()  # Output: "The engine is running!"
    my_electric_car.start_engine()  # Output: "The electric engine is running silently!"
@jonathanhle
Copy link
Author

jonathanhle commented Oct 29, 2023

class vs static methods example to add: https://www.geeksforgeeks.org/class-method-vs-static-method-python/#:~:text=Below%20is%20the,Python3

# Python program to demonstrate
# use of class method and static method.
from datetime import date


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

	# a class method to create a Person object by birth year.
	@classmethod
	def fromBirthYear(cls, name, year):
		return cls(name, date.today().year - year)

	# a static method to check if a Person is adult or not.
	@staticmethod
	def isAdult(age):
		return age > 18


person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)

print(person1.age)
print(person2.age)

# print the result
print(Person.isAdult(22))

Outputs:

21
25
True

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment