Instance variables and methods
In this course, we’ll dive into the exciting world of Python programming and explore the concepts of instance variables and methods. These are fundamental building blocks in Python that allow us to create dynamic and interactive programs. We’ll start from scratch, assuming no prior knowledge, and gradually build up our understanding through clear explanations, fun examples, and engaging practice questions.
1. Introduction to Objects:
- Objects: In programming, an object is a collection of data (variables) and methods (functions) that act on the data. Objects are used to model real-world entities and concepts in a program.
- Classes: A class is like a blueprint or template for creating objects. It defines the structure and behavior of objects of that type.
2. Instance Variables:
- Instance Variables: Also known as attributes, instance variables are unique to each object of a class. They store data that is specific to each instance of the class.
- Declaration and Initialization: To create an instance variable, you declare it within the class definition and initialize it using the special method
__init__()
(constructor) when creating an object. - Role of Instance Variables: Instance variables hold information that distinguishes one object from another, allowing objects of the same class to have different states.
- Let’s see an example:
class Car:
def __init__(self, brand, model):
self.brand = brand # Instance variable
self.model = model # Instance variable
# Creating instances of Car
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Accord")
print(car1.brand) # Output: Toyota
print(car2.model) # Output: Accord
3. Instance Methods:
- Instance Methods: Instance methods are functions defined within a class that operate on instance variables. They can access and manipulate the data stored in instance variables.
- Declaration and Calling: Instance methods are defined like regular functions within the class definition, with the first parameter conventionally named
self
. They are called on objects of the class using dot notation. - Manipulating Instance Variables: Instance methods often work with instance variables to perform specific actions or calculations based on the object’s state.
- Let’s define a class with an instance method:
class Person:
def __init__(self, name):
self.name = name # Instance variable
def greet(self):
return f"Hello, my name is {self.name}"
# Creating instances of Person
person1 = Person("Alice")
person2 = Person("Bob")
print(person1.greet()) # Output: Hello, my name is Alice
print(person2.greet()) # Output: Hello, my name is Bob
Practice Questions:
- Question 1: Write a Python class
Rectangle
with instance variableslength
andwidth
. Define an instance methodcalculate_area()
that returns the area of the rectangle.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
# Test the class
rectangle1 = Rectangle(5, 4)
print("Area of rectangle:", rectangle1.calculate_area()) # Output: 20
- Question 2: Create a Python class
BankAccount
with instance variablesbalance
andaccount_number
. Define instance methodsdeposit(amount)
andwithdraw(amount)
to deposit and withdraw money from the account. Ensure that the balance cannot go below zero during a withdrawal.
class BankAccount:
def __init__(self, account_number, initial_balance=0):
self.account_number = account_number
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
return amount
else:
print("Insufficient funds!")
# Test the class
account1 = BankAccount("12345", 100)
print("Initial balance:", account1.balance) # Output: 100
account1.deposit(50)
print("After deposit:", account1.balance) # Output: 150
withdrawn_amount = account1.withdraw(70)
print("Withdrawn amount:", withdrawn_amount) # Output: 70
print("After withdrawal:", account1.balance) # Output: 80
account1.withdraw(1000) # Output: Insufficient funds!
- Question 3:
# Create a class called 'Dog' with an instance variable 'name'.
# Initialize the 'name' variable with a value "Buddy".
# Define an instance method 'bark()' that prints "Woof! My name is <name>."
# Your code here
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print("Woof! My name is", self.name)
# Test the class
my_dog = Dog("Buddy")
my_dog.bark() # Output: Woof! My name is Buddy
- Question 4:
# Create a class called 'Circle' with instance variables 'radius' and 'color'.
# Initialize 'radius' with a value 5 and 'color' with "red".
# Define an instance method 'area()' that calculates and returns the area of the circle.
# Your code here
import math
class Circle:
def __init__(self, radius, color):
self.radius = radius
self.color = color
def area(self):
return math.pi * self.radius ** 2
# Test the class
my_circle = Circle(5, "red")
print("Area of the circle:", my_circle.area()) # Output: Area of the circle: 78.53981633974483
By the end of this course, you will have a solid understanding of instance variables and methods in Python. You’ll be able to create your own classes, define instance variables to store data unique to each object, and implement instance methods to perform specific actions within your programs. With practice, you’ll become proficient in using these fundamental concepts to build more complex and interactive Python applications.
Now, let’s dive into the exciting world of Python programming and unleash your creativity!