Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Creating Class in Python

This document provides a comprehensive guide on creating classes in Python, explaining the structure, behavior, and the role of constructors. It includes practical examples such as a Person class, Car class, and BankAccount class to illustrate the concepts. The guide emphasizes the importance of understanding classes, constructors, and their public interfaces in object-oriented programming.

Uploaded by

Abdul Basit Butt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Creating Class in Python

This document provides a comprehensive guide on creating classes in Python, explaining the structure, behavior, and the role of constructors. It includes practical examples such as a Person class, Car class, and BankAccount class to illustrate the concepts. The guide emphasizes the importance of understanding classes, constructors, and their public interfaces in object-oriented programming.

Uploaded by

Abdul Basit Butt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Creating Class in Python

Introduction

In Python, a class is a blueprint or template for creating objects. It defines the structure and
behavior of those objects. This guide will walk you through creating a simple class, defining its
public interface, and understanding constructors.

Creating a Simple Class

To create a class in Python, you use the class keyword, followed by the class name. A class
typically contains attributes (data) and methods (functions) that operate on that data. Here's a
basic class structure:

python
class ClassName:
def __init__(self):
# Constructor (optional)
self.attribute1 = value1
self.attribute2 = value2

def method1(self):
# Method 1
# Access and manipulate attributes
pass

def method2(self):
# Method 2
pass
Constructors

A constructor is a special method in a class that is automatically called when an object of the
class is created. It is used to initialize attributes or perform any setup required for the object. In
Python, the constructor method is named __init__ and is always the first method to be called
when an object is created.

python
class MyClass:
def __init__(self, param1, param2):
self.attribute1 = param1
self.attribute2 = param2

# Creating an object and calling the constructor


obj = MyClass("value1", "value2")

Example

Let's implement a simple class called Person to understand the concepts discussed above:

python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def say_hello(self):
return f"Hello, my name is {self.name} and I'm {self.age} years old."

# Creating a Person object


alice = Person("Alice", 30)

# Accessing attributes and methods


print(alice.name) # Output: "Alice"
print(alice.say_hello()) # Output: "Hello, my name is Alice and I'm 30 years
old."
Summary of Important Terms

1. Class: A class is a blueprint or template for creating objects. It defines the structure and
behavior that the objects of the class will have. It's like a recipe for creating objects with
specific attributes and methods.
2. Constructor: A constructor is a special method in a class that is automatically called
when you create an object (instance) of that class. In Python, the constructor method is
named __init__. It is used to initialize the object's attributes, setting their initial values.
3. Object (Instance): An object, also known as an instance, is a specific individual entity
created from a class. Objects are concrete instances of a class, and they have their own set
of attributes and can perform actions defined by the class's methods.

Here's a simplified breakdown of the differences:

● Class is the blueprint, defining what attributes and methods an object will have.

● Constructor (__init__ method) is a special method within a class responsible for


initializing the object's attributes when it is created.

● Object (Instance) is the actual, concrete instance created from the class, with its specific
attribute values as defined by the constructor.

Let's illustrate this with a practical example:

python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# Creating objects (instances) of the Person class


alice = Person("Alice", 30)
bob = Person("Bob", 25)

In this example:
● Person is the class, defining the structure of a person with attributes name and age.

● __init__ is the constructor method, initializing the name and age attributes when
creating a Person object.

● alice and bob are objects (instances) of the Person class, each with its unique name and
age attributes.

More Examples (Practice strongly recommended)

Let's explore a few more examples to illustrate the concepts of creating classes, defining public
interfaces, and using constructors in Python.

Example 1: A Simple Car Class


python
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.speed = 0

def start(self):
print(f"{self.year} {self.make} {self.model} is starting.")

def accelerate(self, increment):


self.speed += increment
print(f"The car is now moving at {self.speed} mph.")

def brake(self, decrement):


self.speed -= decrement
print(f"The car is slowing down to {self.speed} mph.")

# Create a Car object


my_car = Car("Toyota", "Camry", 2022)

# Using the methods


my_car.start()
my_car.accelerate(30)
my_car.brake(10)

Example 2: A BankAccount Class


python
class BankAccount:
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder
self.balance = balance

def deposit(self, amount):


self.balance += amount
print(f"Deposited ${amount}. New balance: ${self.balance}")

def withdraw(self, amount):


if self.balance >= amount:
self.balance -= amount
print(f"Withdrew ${amount}. New balance: ${self.balance}")
else:
print("Insufficient funds. Withdrawal failed.")

# Create a BankAccount object


my_account = BankAccount("Alice", 1000)

# Using the methods


my_account.deposit(500)
my_account.withdraw(200)
my_account.withdraw(800)

Example 3: A Rectangle Class


python
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height

def perimeter(self):
return 2 * (self.width + self.height)

# Create a Rectangle object


my_rectangle = Rectangle(5, 10)

# Using the methods to calculate area and perimeter


print(f"Area: {my_rectangle.area()} square units")
print(f"Perimeter: {my_rectangle.perimeter()} units")

Example 4: A Student Class


python
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self.grades = []

def add_grade(self, grade):


self.grades.append(grade)

def average_grade(self):
if len(self.grades) == 0:
return 0
return sum(self.grades) / len(self.grades)

# Create Student objects


student1 = Student("Alice", 12345)
student2 = Student("Bob", 54321)

# Adding grades
student1.add_grade(85)
student1.add_grade(90)
student2.add_grade(78)
student2.add_grade(92)

# Calculate and display average grades


print(f"{student1.name}'s average grade: {student1.average_grade()}")
print(f"{student2.name}'s average grade: {student2.average_grade()}")

Example 5: A Book Class


python
class Book:
def __init__(self, title, author, ISBN):
self.title = title
self.author = author
self.ISBN = ISBN

def display_info(self):
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print(f"ISBN: {self.ISBN}")

# Create Book objects


book1 = Book("To Kill a Mockingbird", "Harper Lee", "978-0-06-112008-4")
book2 = Book("1984", "George Orwell", "978-0-452-28423-4")

# Display book information


book1.display_info()
book2.display_info()

Example 6: A Person Class with Inheritance


python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def introduce(self):
print(f"Hi, I'm {self.name} and I'm {self.age} years old.")

class Employee(Person):
def __init__(self, name, age, employee_id):
super().__init__(name, age)
self.employee_id = employee_id

def introduce(self):
print(f"Hello, I'm {self.name}, {self.age} years old, and my employee
ID is {self.employee_id}.")

# Create Person and Employee objects


person1 = Person("Alice", 30)
employee1 = Employee("Bob", 25, "E12345")

# Introduce themselves
person1.introduce()
employee1.introduce()

These examples demonstrate how to create classes for various real-world scenarios, define their
public interfaces, and utilize constructors to initialize objects and their attributes.

7. Conclusion
Creating classes in Python is a fundamental concept in object-oriented programming.
Understanding the public interface and constructors is essential for designing effective classes.
You can use these classes to model real-world entities and encapsulate data and behavior within
them.

You might also like