Python Object-Oriented Programming Examples - From Concepts to Code!

파이썬 객체지향 프로그래밍 예제 참고 이미지

Python Object-Oriented Programming Examples - Learn OOP from the Basics to the Real World!

PythonI've often wondered: "My code is getting too long and complicated because I've been writing in a procedural way... should I switch to object-oriented?" 🤔 🤔 I'm not sure if I'll be able to do that.

Python supports both procedural and object-oriented styles, but learning Python object-oriented programming (OOP) will make your code cleaner and easier to maintain.

In this article, we'll use the Basic concepts and uses of OOP with Python object-oriented programming examples.and we'll also learn about Features of Python as an object-oriented language versus Python's object-oriented procedural approachWe'll also take a look at the code examples, which are easy to follow, so stick with us!

What is the Python Object-Oriented Language?

Object-oriented programming (OOP) is a way of designing programs by dividing them into units called "objects". Python is one of the leading object-oriented languages, using classes and objects to handle data.

Features of Python's Object-Oriented Language

  1. Classes and objects: Structure your data and make it more reusable.
  2. EncapsulationProtect sensitive data and restrict access from the outside.
  3. Inheritance: You can easily extend new classes based on existing classes.
  4. Polymorphism: Makes the same method name behave differently depending on the class.

Python Object-Oriented vs. Procedural Oriented

파이썬 객체지향 절차지향 비교 이미지

Compare with tables

FeaturesProcedure-orientedObject-oriented
How we handle dataProcess data into functions and variablesBundle data into objects for processing
How to write codeWrite in a sequential flowLeverage encapsulation and inheritance to write structured code
Code reusabilityLow reusabilityReuse code with encapsulation and inheritance
MaintainabilityComplexity increases with longer codeEasy to maintain and highly scalable
Key use casesWrite simple scripts, quick test codeLarge-scale software design, complex data modeling


Procedure-driven programmingtreats data as functions and variables, and writes code in a sequential flow. This approach is great for solving simple problems quickly, but as code gets longer and more complex, it can become harder to maintain and less reusable.

Whereas, Object-oriented programmingbundles data into objects and utilizes encapsulation and inheritance to make code more reusable and extensible. Object orientation is a particularly powerful tool for large-scale software development because it's easy to maintain and allows for a wide range of feature extensions.

For example, this is what happens when you implement a dog's behavior in a procedure-oriented way:

# Procedure Oriented Method
name = "Buddy"
breed = "Jindo"
def bark():
    return f"{name} barks loudly!"

print(bark())

The object-oriented approach is cleaner:

# Object-Oriented Method
class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        return f"{self.name} barks loudly!"

my_dog = Dog("Buddy", "Jindo")
print(my_dog.bark())

Python Object-Oriented Programming Examples

1. Class and object examples

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

    def introduce(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

person = Person("Charlie", 25)
print(person.introduce())

Code commentary

  1. __init__ Methods: Initialization method at object creation time, setting the name and age.
  2. self: References the object itself, accessing its properties and methods.
  3. introduce MethodsMethods that print information about the object.

2. inheritance example

클래스 상속 구조 이미지
class Animal:
    def speak(self):
        return "Makes a sound."

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

dog = Dog()
cat = Cat()
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!

Code commentary

  1. Parent Class AnimalDefine a common behavior (vocalization) for all animals.
  2. Child Classes Dogand Cat: parent class's speak method (overriding).
  3. Polymorphism: The same method name (speak) behaves differently depending on this class.

3. encapsulation example

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance # Private attribute

    def deposit(self, amount):
        self.__balance += amount
        return f"Deposited {amount}. Balance: {self.__balance}."

    def withdraw(self, amount):
        if self.__balance >= amount:
            self.__balance -= amount
            return f"Withdrew {amount}. Balance: {self.__balance}."
        else:
            return "Insufficient funds!"

account = BankAccount("Alice", 10000)
print(account.deposit(5000))
print(account.withdraw(7000))
Code commentary
  1. __balance: Declared as a Private property that cannot be accessed from outside.
  2. depositand withdraw MethodsSecurely manage the balance of your bank account.
  3. Encapsulation: Protect data, allowing access through methods if necessary.

Finalize

In this article, you learned the basic concepts and uses of OOP through examples of object-oriented programming in Python. You've seen the strengths of Python as an object-oriented language and the differences between Python's object-oriented procedural approach and object-oriented programming. By mastering object-oriented programming, you'll be able to write cleaner, more maintainable code.

Now follow along and feel the Python OOP magic for yourself! And 😄 and 😄 and 😄. Python ORM - Django ORM and SQL, the pros and cons in a nutshell! Check out the post to learn more about databases!

# Glossary

Glossary (for beginners)

1. select Object
  • A unit that is a code representation of a real-world object or concept.
  • Objects have Attributes and Methods.
    • Attributes: The state or data of an object.
    • Method: An action or function that an object can perform.
2. click Class
  • A blueprint for creating an object.
  • Classes define properties and methods, which allow you to create multiple objects.
3. click Instance
  • An individual object created from a class.
  • A class is a blueprint, and an instance is an entity created from that blueprint.
4. Inheritance
  • The ability to create a new class (child class) based on an existing class (parent class).
  • Increase code reusability and make it easy to extend functionality.
5. Encapsulation
  • The concept of protecting properties inside an object from direct access from the outside.
  • Mainly Private property, which controls access using getter/setter methods.
6. Polymorphism
  • The ability to make methods with the same name behave differently depending on the class.
  • It is implemented by overriding (overriding) methods defined in the parent class in the child class.
7. __init__ Methods
  • The initialization method that is automatically called when the object is created.
  • Used to initialize or set a default value for an object's properties.
8. self
  • A keyword that refers to the object itself, used to access properties and methods from inside the class.
  • All instance methods take a selfto use the
9. Overriding
  • This means overriding a method of the parent class in a child class.
  • Methods with the same name are implemented to behave differently in the parent and child classes.
테리 이모티콘
(Happy coding!)

Similar Posts