Thinking Like a Programmer•Interactive notebook lesson•Free
Classes, self, other
No account is required. Learn the material, try the examples, and mark it complete when you are ready to move on. Sign in with email only if you want to save progress across devices.
Classes
Classes can be understood as a data type. It is not a data type, but for intuition can be assumed as a custom data type.
Like for example, here we will create a custom data type Animal which will have features just like an animal does.
Codepython
"ASHISH".lower()Output
'ashish'Codepython
class Animal:
"""A class representing an animal with a strength attribute."""
strength = 10 # Default strength value for all animals
def strength_plus(self, strength_points):
"""
Increases the animal's strength by a given amount.
Parameters:
strength_points (int or float): The amount to increase strength by.
"""
self.strength = self.strength + strength_points # Update the strength attribute
Codepython
animal1 = Animal()
animal1.strength_plus(1000)
animal1.strengthOutput
1010Codepython
Codepython
panda = Animal() # creating an instance of the Animal classCodepython
Codepython
print(f"Initial strength of panda: {panda.strength}") # Output: 10 (default strength)
panda.strength_plus(5) # Increases strength by 5
print(f"Strength of panda after increase: {panda.strength}") # Output: 15
Output
Initial strength of panda: 10
Strength of panda after increase: 15
Codepython
panda.strength_plus(10)Codepython
panda.strengthOutput
25Codepython
bitt = Animal()
print(bitt.strength)Output
10
Codepython
Codepython
# Define a class named 'Species'
class Species():
# The __init__ method is the constructor that initializes the object
# It takes type_of_species, name, and power as arguments when creating an instance of the class
def __init__(self, type_of_species, name, power):
# Initialize instance variables with the provided values
self.type_of_species = type_of_species # Set the 'type_of_species' (e.g., animal type)
self.name = name # Set the 'name' of the species
self.power = power # Set the 'power' attribute of the species
# Define a class variable 'strength' with a default value of 10
strength = 10
# Method to increase the 'strength' by a given value 'strength_points'
def strength_plus(self, strength_points):
# Add the value of 'strength_points' to the 'strength' attribute
self.strength = self.strength + strength_points
# The __add__ method allows the use of the + operator to add two 'Species' objects
# It returns the sum of their 'power' attributes
def __add__(self, other):
# 'self' refers to the current instance, and 'other' refers to the second instance
return self.power + other.power
Codepython
# Create an instance of the Species class
# The arguments "Panda", "Bill", and 50 are passed to the constructor (__init__) to initialize the object
var1 = Species("Panda", "Bill", 50)
Codepython
# Access the 'name' attribute of the var1 object
print(var1.name) # Output: "Bill"
Output
Bill
Codepython
# Access the 'type_of_species' attribute of the var1 object
print(var1.type_of_species) # Output: "Panda"
Output
Panda
Codepython
# Access the 'power' attribute of the var1 object
print(var1.power) # Output: 50
Output
50
Codepython
# Access the 'strength' attribute of the var1 object
print(var1.strength) # Output: 10
Output
10
Codepython
# Decrease the strength by 10
var1.strength_plus(-10)
# Access the 'strength' attribute of var1 after the update
print(var1.strength) # Output: 0
Output
0
Codepython
Codepython
# Create a second instance of the Species class with type "Cat", name "FoxyPirates", and power 5
var2 = Species("Cat", "FoxyPirates", 5)
Codepython
var1+var2Output
55Codepython
# Accessing the 'type_of_species', 'name', and 'power' attributes of var2
print(f"Species Type: {var2.type_of_species}") # Output: "Cat"
print(f"Species Name: {var2.name}") # Output: "FoxyPirates"
print(f"Species Power: {var2.power}") # Output: 5
# Accessing the default strength attribute of var2
print(f"Species Strength: {var2.strength}") # Output: 10
Output
Species Type: Cat
Species Name: FoxyPirates
Species Power: 5
Species Strength: 10
Codepython
var2.strengthOutput
10Codepython
var1.strengthOutput
0Codepython
# Create a third instance of the Species class with type "Cat", name "naniPirates", and power 13
var3 = Species("Cat", "naniPirates", 13)
Codepython
var3.strengthOutput
10Codepython
var1.powerOutput
50Codepython
var3.powerOutput
13Codepython
# Adding var1 and var3, which will sum their 'power' attributes
result = var1 + var3
# Printing the result
print(f"The sum of var1 and var3 power is: {result}") # Output: 63
Output
The sum of var1 and var3 power is: 63
Codepython
# Explicitly calling the __add__ method to add var1 and var3
result = var1.__add__(var3)
# Printing the result
print(f"The sum of var1 and var3 power is: {result}") # Output: 63
Output
The sum of var1 and var3 power is: 63
Codepython
# Define a class named 'Butterfly'
class Butterfly():
# The __init__ method is the constructor that initializes the object
# It takes name, color, and season as arguments. If season is not provided, it defaults to 'Autumn'.
def __init__(self, name, color, season='Autumn'):
self.name = name # Set the 'name' of the butterfly
self.color = color # Set the 'color' of the butterfly
self.season = season # Set the 'season' of the butterfly (default is 'Autumn')
# Define a class variable 'beauty_points' with a default value of 100
beauty_points = 100
# Method to increase or decrease the 'beauty_points' by a given value 'points'
# The 'increase' argument controls whether to add or subtract points
def beauty_plus(self, points, increase=True):
if increase:
self.beauty_points += points # Increase beauty_points by 'points' if 'increase' is True
else:
self.beauty_points -= points # Decrease beauty_points by 'points' if 'increase' is False
# The __add__ method allows the use of the + operator to add two 'Butterfly' objects
# It returns the sum of their 'beauty_points' attributes
def __add__(self, other):
# 'self' refers to the current instance, and 'other' refers to the second instance
return self.beauty_points + other.beauty_points
Codepython
# Create an instance of Butterfly with name 'Queen Bee' and color 'Golden Blue'
queenB = Butterfly('Queen Bee', 'Golden Blue')
Codepython
queenBOutput
<__main__.Butterfly at 0x205a2064650>Codepython
# Accessing the 'season' attribute of queenB
print(queenB.season) # Output: "Autumn"
Output
Autumn
Codepython
# Subtracting 20 from beauty_points
queenB.beauty_plus(20, False)
# Accessing the updated beauty_points
print(queenB.beauty_points) # Output: 80
Output
80
Codepython
# Adding 50 to beauty_points
queenB.beauty_plus(50, True)
# Accessing the updated beauty_points
print(queenB.beauty_points) # Output: 130
Output
130
Codepython
queenB.beauty_pointsOutput
130Codepython
queenB.beauty_plus(1, False)Codepython
queenB.beauty_pointsOutput
129Codepython
# Create an instance of Butterfly with name 'Arthur', color 'Blood Red', and season 'Winter'
kingB = Butterfly('Arthur', 'Blood Red', 'Winter')
Codepython
# Accessing the 'beauty_points' attribute of kingB
print(kingB.beauty_points) # Output: 100
Output
100
Codepython
# Adding the beauty points of queenB and kingB
total_beauty = queenB + kingB
# Printing the result
print(f"Total beauty points: {total_beauty}") # Output: 229
Output
Total beauty points: 229
Codepython
queenB.__add__(kingB)Output
229Codepython
kingB.__add__(queenB)Output
229Codepython
queenB.beauty_points - kingB.beauty_pointsOutput
29Codepython
Finished this lesson?
Keep your place here, or save it across devices with an email link.
Saved in this browser. Save progress with email →