Example 1:Defining a Simple Class

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

    def bark(self):
        return "Woof!"

# Create an instance of Dog/code created by Pycent.com
my_dog = Dog("Buddy")
print(my_dog.bark())  
# Outputs: Woof!          

Python OOP - Dog Class Explanation

1. Class Definition:

class Dog:

This line starts the definition of a new class called Dog. Think of a class as a blueprint for creating objects. Each object created from this class will be an instance of Dog.

def __init__(self, name):

This method is a special method called the constructor. Every time a new Dog object is created, this method is automatically called. The self parameter refers to the instance of the class; it's a way to access variables and methods associated with the current object.

self.name = name

This line sets an attribute name of the Dog instance. When a new Dog object is created, it is initialized with a name that you provide. This attribute can then be used in other methods of the class or directly on the class instance.

2. Method Definition:

def bark(self):

This is a method of the class Dog. Methods are functions that are defined inside a class and describe the behaviors of the class objects.

return "Woof!"

When this method is called, it returns the string "Woof!". This is simulating the barking behavior of a dog.

3. Creating an Instance of Dog:

my_dog = Dog("Buddy")

Here, my_dog is an instance of the Dog class, created with the name "Buddy". This calls the __init__ method of Dog with "Buddy" as the argument for the name parameter.

4. Using the Dog instance:

print(my_dog.bark()) # Outputs: Woof!

my_dog.bark(): This line calls the bark method on the my_dog object. Since the bark method returns the string "Woof!", this string is then printed to the console.

So, in summary, this code defines a Dog class that can hold a name and perform an action (bark). A Dog instance is then created with the name "Buddy", and it performs the action by "barking," which results in printing "Woof!" to the console. This is a simple example of using classes to model real-world concepts in a structured way with object-oriented programming.

Example 2:Adding More Attributes

      
          class Cat:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def meow(self):
        return "Meow!"

# Create a Cat instance
my_cat = Cat("Whiskers", "black")
print(my_cat.name, my_cat.color)  # Outputs: Whiskers black
          

Example 3: Using Class Attributes

      
          class Bird:
    species = "parrot"  # Class attribute

    def __init__(self, name):
        self.name = name  # Instance attribute

# Instances of Bird
bird1 = Bird("Tweety")
bird2 = Bird("Polly")

print(Bird.species)  # Outputs: parrot
          

Example 4:Methods That Use Self Attributes

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

    def display_info(self):
        return f"This car is a {self.year} {self.brand}."

# Using the class
my_car = Car("Toyota", 2021)
print(my_car.display_info())  # Outputs: This car is a 2021 Toyota.
          

Example 5: Inheritance

      
          class Animal:
    def speak(self):
        return "Some sound"

class Duck(Animal):  # Inherits from Animal
    def speak(self):
        return "Quack!"

# Using the derived class
my_duck = Duck()
print(my_duck.speak())  # Outputs: Quack!
          

Example 6: Multiple Methods in a Class

      
          class Calculator:
    def add(self, x, y):
        return x + y

    def multiply(self, x, y):
        return x * y

# Use the Calculator class
calc = Calculator()
print(calc.add(5, 3))       # Outputs: 8
print(calc.multiply(4, 2))  # Outputs: 8
          

Example 7: Class Method and Static Method

      
          class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @staticmethod
    def area(width, height):
        return width * height

# Static method can be called without creating an instance
print(Rectangle.area(10, 20))  # Outputs: 200
          

Example 8: Encapsulation Using Private Attributes

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

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            print("Deposit successful!")

# Using the Account class
acc = Account("John")
acc.deposit(100)
          

Example 9: Property Decorators (Getters and Setters)

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

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if value > 0:
            self._age = value
        else:
            print("Age must be positive!")

# Using getters and setters
p = Person("Alice", 30)
print(p.age)  # Outputs: 30
p.age = -5    # Outputs: Age must be positive!
          

Example 10: Overriding Methods

      
          class Parent:
    def greet(self):
        return "Hello!"

class Child(Parent):
    def greet(self):
        return "Hey there!"

# Using the classes
parent = Parent()
child = Child()
print(parent.greet())  # Outputs: Hello!
print(child.greet())   # Outputs: Hey there!