A Python class is a blueprint for creating objects. Objects have properties and behaviors, which in Python are represented by variables and methods defined in the class. The class defines the object's structure, while an instance of a class is a specific object created from that class.
In a Python class, the init method is known as the initializer or constructor and is automatically called when a new instance of the class is created. It is typically used to initialize the instance variables of the object.
Here is a simple example of a Python class:
class Dog:
# Initializer / Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def bark(self):
return f"{self.name} says woof!"
In this Dog class, each dog has a name and an age, which are instance attributes, and a behavior represented by the bark method.
Exercise 1: Create a class Car with instance attributes make and model, and a method honk that prints "Beep beep!"
# Write your Car class here
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def honk(self):
print("Beep beep!")
Explanation: In this exercise, you would create a Car class where each car object can store its make and model, and has a honk method that simulates the car horn.
Exercise 2: Create a class Calculator with a method add that takes two numbers and returns their sum.
class Calculator:
@staticmethod
def add(num1, num2):
return num1 + num2
Explanation: The Calculator class provides a static method add that can be called without creating an instance of the class. It takes two parameters and returns their sum.
Comments