from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self, name: str):
self.name = name
super().__init__()
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print(f'{self.name} says: Woof')
class Cat(Animal):
def make_sound(self):
print(f'{self.name} says: Meows')
Dog('Pepper').make_sound()
Cat('Bella').make_sound()
class Solver:
def __init__(self, nums: list):
self.nums = nums
@classmethod
def get_even(cls, nums: list):
return cls([num for num in nums if num % 2 == 0])
def print_output(self):
print("Result:", self.nums)
# Not using class method
nums = [1, 2, 3, 4, 5, 6, 7]
solver = Solver(nums).print_output()
solver2 = Solver.get_even(nums)
solver2.print_output()
class Food:
def __init__(self, name: str, color: str):
self.name = name
self.color = color
apple = Food("apple", "red")
print("The color of apple is", getattr(apple, "color", "yellow"))
print("The flavor of apple is", getattr(apple, "flavor", "sweet"))
class DataLoader:
def __init__(self, data_dir: str):
self.data_dir = data_dir
print("Instance is created")
def __call__(self):
print("Instance is called")
data_loader = DataLoader("my_data_dir")
# Instance is created
data_loader()
# Instance is called
import re
class ProcessText:
def __init__(self, text_column: str):
self.text_column = text_column
@staticmethod
def remove_URL(sample: str) -> str:
"""Replace url with empty space"""
return re.sub(r"http\S+", "", sample)
text = ProcessText.remove_URL("My favorite page is https://www.google.com")
print(text)
class Fruit:
def __init__(self, name: str, color: str):
self._name = name
self._color = color
@property
def color(self):
print("The color of the fruit is:")
return self._color
@color.setter
def color(self, value):
print("Setting value of color...")
if self._color is None:
if not isinstance(value, str):
raise ValueError("color must be of type string")
self.color = value
else:
raise AttributeError("Sorry, you cannot change a fruit's color!")
fruit = Fruit("apple", "red")
fruit.color
fruit.color = "yellow"
class Food:
def __init__(self, name: str, color: str):
self.name = name
self.color = color
def __str__(self):
return f"{self.color} {self.name}"
def __repr__(self):
return f"Food({self.color}, {self.name})"
food = Food("apple", "red")
print(food) # str__
food # __repr__