Python Tips DS
Python Tips DS
Python Class
GitHub View on GitHub Book View Book
Inheritance in Python
Have you ever had multiple classes that have similar attributes
and methods? In the code below, the class Dachshund and Poodle
have similar attributes (color) and methods (show_info).
class Dachshund:
def __init__(self, color: str):
self.color = color
def show_info(self):
print(f"This is a Dachshund with
{self.color} color.")
class Poodle:
def __init__(self, color: str):
self.color = color
def show_info(self):
print(f"This is a Poodle with
{self.color} color.")
bim = Dachshund("black")
bim.show_info()
In the code below, we define the parent class to be Dog and the
child classes to be Dachshund and Poodle. With class inheritance,
we avoid repeating the same piece of code multiple times.
class Dog:
def __init__(self, type_: str, color: str):
self.type = type_
self.color = color
def show_info(self):
print(f"This is a {self.type} with
{self.color} color.")
class Dachshund(Dog):
def __init__(self, color: str):
super().__init__(type_="Dachshund",
color=color)
class Poodle(Dog):
def __init__(self, color: str):
super().__init__(type_="Poodle",
color=color)
bim = Dachshund("black")
bim.show_info()
coco = Poodle("brown")
coco.show_info()
class Animal(ABC):
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)
Result: [1, 2, 3, 4, 5, 6, 7]
Result: [2, 4, 6]
getattr: a Better Way to Get the Attribute of
a Class
If you want to get a default value when calling an attribute that is
not in a class, use getattr() method.
print(
"The color of apple is",
getattr(apple, "color", "yellow")
)
print(
"The flavor of apple is",
getattr(apple, "flavor", "sweet")
)
-------------------------------------------------
--------------------------
AttributeError
Traceback (most recent call last)
/tmp/ipykernel_337430/3178150741.py in <module>
----> 1 print("The flavor of apple is",
apple.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
Instance is created
Instance is called
Static method: use the function without
adding the attributes required for a new
instance
Have you ever had a function in your class that doesn’t access any
properties of a class but fits well in a class? You might find it
redundant to instantiate the class to use that function. That is
when you can turn your function into a static method.
All you need to turn your function into a static method is the
decorator @staticmethod. Now you can use the function without
adding the attributes required for a new instance.
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)
My favorite page is
Property Decorator: A Pythonic Way to Use
Getters and Setters
If you want users to use the right data type for a class attribute or
prevent them from changing that attribute, use the property
decorator.
In the code below, the first color method is used to get the
attribute color and the second color method is used to set the
value for the attribute color.
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!")
'red'
fruit.color = "yellow"
Setting value of color...
-------------------------------------------------
--------------------------
AttributeError
Traceback (most recent call last)
/tmp/ipykernel_337430/2513783301.py in <module>
----> 1 fruit.color = "yellow"
/tmp/ipykernel_337430/2891187161.py in
color(self, value)
17 self.color = value
18 else:
---> 19 raise AttributeError("Sorry,
you cannot change a fruit's color!")
20
21
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__
red apple
food # __repr__
Food(red, apple)