Level 1: Basic Class Creation and Instantiation
# Defining a basic class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an instance
my_dog = Dog('Buddy', 3)
# Accessing attributes
print(my_dog.name)
print(my_dog.age)
#clcoding.com
Buddy
3
Level 2: Methods and Instance Variables
# Defining a class with methods
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
# Creating an instance and calling a method
my_dog = Dog('Buddy', 3)
my_dog.bark()
#clcoding.com
Buddy says woof!
Level 3: Class Variables and Class Methods
# Defining a class with class variables and methods
class Dog:
species = 'Canis familiaris' # Class variable
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
@classmethod
def get_species(cls):
return cls.species
# Accessing class variables and methods
print(Dog.species)
print(Dog.get_species())
#clcoding.com
Canis familiaris
Canis familiaris
Level 4: Inheritance and Method Overriding
# Base class and derived classes
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return f"{self.name} says woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says meow!"
# Instances of derived classes
my_dog = Dog('Buddy')
my_cat = Cat('Whiskers')
# Calling overridden methods
print(my_dog.speak())
print(my_cat.speak())
#clcoding.com
Buddy says woof!
Whiskers says meow!
Level 5: Advanced Features (Polymorphism, Abstract Base Classes, Mixins)
from abc import ABC, abstractmethod
# Abstract base class
class Animal(ABC):
@abstractmethod
def speak(self):
pass
# Derived classes implementing the abstract method
class Dog(Animal):
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof!"
class Cat(Animal):
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says meow!"
# Polymorphism in action
def animal_speak(animal):
print(animal.speak())
# Creating instances
my_dog = Dog('Buddy')
my_cat = Cat('Whiskers')
# Using polymorphism
animal_speak(my_dog)
animal_speak(my_cat)
Buddy says woof!
Whiskers says meow!
0 Comments:
Post a Comment