0% found this document useful (0 votes)
5 views15 pages

Python Class Examples and Usage

introduction to python

Uploaded by

chetanbhone025
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views15 pages

Python Class Examples and Usage

introduction to python

Uploaded by

chetanbhone025
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

class Student:

# Constructor to initialize attributes


def __init__(self, name, roll_no):
[Link] = name
self.roll_no = roll_no

# Method to display student information


def display(self):
print(“Student Name:”, [Link])
print(“Roll Number:”, self.roll_no)

# Creating objects (instances of Student class)


s1 = Student(“Rahul”, 101)
s2 = Student(“Priya”, 102)

# Method call using objects


[Link]()
[Link]()

-----------------------------------------------------

class Student:
def __init__(self, name, roll_no): # constructor
[Link] = name
self.roll_no = roll_no

def display(self):
print(“Name:”, [Link], “Roll No:”, self.roll_no)

# object creation → constructor runs automatically


s1 = Student(“Rahul”, 101)
[Link]()

-----------------------------------------------------

class Car:
wheels = 4 # class attribute (same for all cars)

def __init__(self, brand, color):


[Link] = brand # instance attribute
[Link] = color # instance attribute

def show(self):
print(“Brand:”, [Link], “Color:”, [Link], “Wheels:”,
[Link])
c1 = Car(“BMW”, “Black”)
c2 = Car(“Audi”, “Red”)

[Link]()
[Link]()

-----------------------------------------------------

class Car:
def __init__(self, brand):
[Link] = brand
print(“Car created:”, [Link])

def __del__(self):
print(“Car destroyed:”, [Link])

c1 = Car(“BMW”) # constructor runs


del c1 # destructor runs here

-----------------------------------------------------

class BankDemo:
# constructor to initialize attributes
def __init__(self, acc_no, name, balance=0):
self.acc_no = acc_no
[Link] = name
[Link] = balance
print(f”Account created for {[Link]} (Acc No: {self.acc_no})
with balance {[Link]}”)

# method to deposit money


def deposit(self, amount):
if amount > 0:
[Link] += amount
print(f”{amount} deposited successfully. New Balance:
{[Link]}”)
else:
print(“Invalid deposit amount!”)

# method to withdraw money


def withdraw(self, amount):
if amount <= [Link]:
[Link] -= amount
print(f”{amount} withdrawn successfully. Remaining Balance:
{[Link]}”)
else:
print(“Insufficient Balance!”)

# method to check balance


def check_balance(self):
print(f”Account Balance for {[Link]}: {[Link]}”)

# Creating object of BankDemo class


acc1 = BankDemo(101, “Rahul”, 5000)

# Performing operations
[Link](2000) # deposit
[Link](1500) # withdraw
acc1.check_balance() # check balance

-----------------------------------------------------

class Student:
# Constructor to initialize values
def __init__(self, first_name, last_name, qualification):
self.first_name = first_name
self.last_name = last_name
[Link] = qualification
print(f”Student record created for {self.first_name}
{self.last_name}”)

# Method to update qualification


def update_qualification(self, new_qualification):
print(f”Updating qualification of {self.first_name}
{self.last_name}...”)
[Link] = new_qualification
print(“Qualification updated successfully!”)

# Method to display student details


def display(self):
print(“\n--- Student Details ---”)
print(“First Name:”, self.first_name)
print(“Last Name:”, self.last_name)
print(“Qualification:”, [Link])

# ---------- Main Program ----------


# Creating student object
s1 = Student(“Rahul”, “Sharma”, “[Link]”)

# Display details before update


[Link]()

# Updating qualification
s1.update_qualification(“MCA”)

# Display details after update


[Link]()

--------------------------------------------------------

class Parent:
# parent code

class Child(Parent):
# child code

--------------------------------------------------------

class Parent: # Superclass


def parent_method(self):
print(“This is a method from Parent class”)

class Child(Parent): # Child inherits Parent


def child_method(self):
print(“This is a method from Child class”)

# Object of Child class


obj = Child()
obj.parent_method() # method from Parent
obj.child_method() # method from Child

--------------------------------------------------------

class Parent:
def show(self):
print(“This is the Parent class method”)

class Child(Parent):
def show(self): # Overriding the parent method
print(“This is the Child class method (overridden)”)
# Testing
p = Parent()
c = Child()

[Link]() # Parent’s method


[Link]() # Child’s method overrides Parent’s

--------------------------------------------------------

class Parent:
def func1(self):
print(“This is Parent class”)

class Child(Parent): # Child inherits Parent


def func2(self):
print(“This is Child class”)

obj = Child()
obj.func1() # Parent method
obj.func2() # Child method

--------------------------------------------------------

class Parent1:
def func1(self):
print(“This is Parent1 class”)

class Parent2:
def func2(self):
print(“This is Parent2 class”)

class Child(Parent1, Parent2): # inherits from both


def func3(self):
print(“This is Child class”)

obj = Child()
obj.func1() # from Parent1
obj.func2() # from Parent2
obj.func3() # own method

--------------------------------------------------------

class Grandparent:
def func1(self):
print(“This is Grandparent class”)

class Parent(Grandparent):
def func2(self):
print(“This is Parent class”)

class Child(Parent):
def func3(self):
print(“This is Child class”)

obj = Child()
obj.func1() # from Grandparent
obj.func2() # from Parent
obj.func3() # from Child

--------------------------------------------------------

class Parent:
def func1(self):
print(“This is Parent class”)

class Child1(Parent):
def func2(self):
print(“This is Child1 class”)

class Child2(Parent):
def func3(self):
print(“This is Child2 class”)

obj1 = Child1()
obj2 = Child2()

obj1.func1(); obj1.func2()
obj2.func1(); obj2.func3()

--------------------------------------------------------

class Parent1:
def func1(self):
print(“This is Parent1 class”)

class Parent2:
def func2(self):
print(“This is Parent2 class”)

class Child1(Parent1):
def func3(self):
print(“This is Child1 class”)

class Child2(Child1, Parent2): # multiple + multilevel


def func4(self):
print(“This is Child2 class”)

obj = Child2()
obj.func1() # from Parent1
obj.func2() # from Parent2
obj.func3() # from Child1
obj.func4() # from Child2

--------------------------------------------------------

class Number:
def __init__(self, value):
[Link] = value

# Overloading + operator
def __add__(self, other):
return [Link] + [Link]

# Creating objects
n1 = Number(10)
n2 = Number(20)

print(n1 + n2) # Works like normal addition

--------------------------------------------------------

class Student:
def __init__(self, name):
[Link] = name # object’s own variable

def show(self): # normal method


print(“Name:”, [Link])

s1 = Student(“Rahul”)
s2 = Student(“Priya”)

[Link]() # prints Rahul


[Link]() # prints Priya

--------------------------------------------------------

class Student:
count = 0 # class variable (same for all students)

def __init__(self, name):


[Link] = name
[Link] += 1 # increase when new student is created

@classmethod
def total_students(cls): # cls = Student class
print(“Total Students:”, [Link])

s1 = Student(“Rahul”)
s2 = Student(“Priya”)

Student.total_students()

--------------------------------------------------------

class Math:
@staticmethod
def add(a, b):
return a + b

@staticmethod
def multiply(a, b):
return a * b

print([Link](5, 10))
print([Link](3, 4))

--------------------------------------------------------

class Printer:
def print_page(self):
print(“Page is printing...”)

class Computer:
def __init__(self):
[Link] = Printer() # has a printer

def print_document(self):
# Delegation → Computer asks Printer to do the task
[Link].print_page()

c1 = Computer()
c1.print_document()
--------------------------------------------------------

class Engine:
def start(self):
print(“Engine started”)

class Car:
def __init__(self):
[Link] = Engine() # Car has an Engine

def drive(self):
[Link]()
print(“Car is moving”)

c1 = Car()
[Link]()

--------------------------------------------------------

import re

pattern = r”abc”
text = “abcdef”

if [Link](pattern, text):
print(“Match found!”)
else:
print(“Match not found!”)

--------------------------------------------------------

import re

pattern = r”abc”
text = “This is a test: abc”

search = [Link](pattern, text)

if search:
print(“Pattern found!”)
else:
print(“Pattern not found!”)

--------------------------------------------------------

import re
text = “The first date is 12-05-2022 and the second date is 15-06-
2021.”

# Regex pattern for matching dates in format DD-MM-YYYY

pattern = r”\d{2}-\d{2}-\d{4}”
dates = [Link](pattern, text)
print(“Dates found:”, dates)

--------------------------------------------------------

import re

text = “You can contact us at info@[Link] or support@[Link].”

# Regex pattern for matching email addresses


pattern = r”[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+”

emails = [Link](pattern, text)

print(“Emails found:”, emails)

--------------------------------------------------------

import re

text = “Check website ://[Link] and follow on


[Link]

# Regex pattern for matching URLs


pattern = r”https?://[a-zA-Z0-9-]+\.[a-zA-Z]{2,}”

urls = [Link](pattern, text)

print(“URLs found:”, urls)

--------------------------------------------------------

import re

def validate_password(password):
# Regex for strong password
pattern = r’^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\
d@$!%*?&]{8,}$’

if [Link](pattern, password):
return “Valid Strong Password”
else:
return “Invalid Password”

# Test the program


print(validate_password(“Rahul@123”)) # strong password
print(validate_password(“rahul123”)) # missing uppercase & special
char
print(validate_password(“RAHUL@123”)) # missing lowercase

--------------------------------------------------------

import re

def validate_email(email):
# Regex pattern for validating email
pattern = r’^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$’

if [Link](pattern, email):
return “Valid Email Address ”
else:
return “Invalid Email Address ”

# Test the program


print(validate_email(“student123@[Link]”)) # valid
print(validate_email(“[Link]@[Link]”)) # valid
print(validate_email(“invalid-email@com”)) # invalid

--------------------------------------------------------

import threading

def task():
print(“Thread is running...”)

# Create thread
t1 = [Link](target=task)

# Start thread
[Link]()

# Wait for thread to finish


[Link]()

----------------------------------------------------------
import threading

balance = 1000 # shared resource

def withdraw(amount):
global balance
for _ in range(3):
balance -= amount
print(“Withdraw:”, amount, “Remaining Balance:”, balance)

# Create threads
t1 = [Link](target=withdraw, args=(200,))
t2 = [Link](target=withdraw, args=(200,))

[Link]()
[Link]()

-------------------------------------------------------

import threading

balance = 1000
lock = [Link]()

def withdraw(amount):
global balance
for _ in range(3):
[Link]() # lock the resource
balance -= amount
print(“Withdraw:”, amount, “Remaining Balance:”, balance)
[Link]() # release the resource

# Create threads
t1 = [Link](target=withdraw, args=(200,))
t2 = [Link](target=withdraw, args=(200,))

[Link]()
[Link]()

--------------------------------------------------------

import threading

def print_numbers():
for i in range(1, 6):
print(“Number:”, i)

def print_letters():
for ch in [‘A’, ‘B’, ‘C’, ‘D’, ‘E’]:
print(“Letter:”, ch)

# Create threads
t1 = [Link](target=print_numbers)
t2 = [Link](target=print_letters)

# Start threads
[Link]()
[Link]()

# Wait for both threads to finish


[Link]()
[Link]()

print(“Both threads finished, program ends here”)

--------------------------------------------------------

import threading
import time

# Create a lock for synchronization


lock = [Link]()

# Thread function for ascending order


def print_ascending():
for i in range(1, 11):
[Link]() # lock before printing
print(“Ascending:”, i)
[Link]() # release lock
[Link](0.3) # small delay for better output

# Thread function for descending order


def print_descending():
for i in range(10, 0, -1):
[Link]()
print(“Descending:”, i)
[Link]()
[Link](0.3)

# Create threads
t1 = [Link](target=print_ascending)
t2 = [Link](target=print_descending)
# Start threads
[Link]()
[Link]()

# Wait for threads to complete


[Link]()
[Link]()

print(“Both threads finished execution”)

--------------------------------------------------------

import threading
import time

# Create a lock for synchronization


lock = [Link]()

# Thread function for printing squares


def print_squares():
for i in range(1, 6):
[Link]() # acquire lock
print(“Square of”, i, “=”, i * i)
[Link]() # release lock
[Link](0.3) # small delay

# Thread function for printing cubes


def print_cubes():
for i in range(1, 6):
[Link]()
print(“Cube of”, i, “=”, i * i * i)
[Link]()
[Link](0.3)

# Create threads
t1 = [Link](target=print_squares)
t2 = [Link](target=print_cubes)

# Start threads
[Link]()
[Link]()

# Wait for threads to finish


[Link]()
[Link]()

print(“Both threads finished execution”)


----------------------------------------------------------

Common questions

Powered by AI

Inheritance in object-oriented programming allows a class to inherit attributes and methods from another class, promoting code reuse. Multi-level inheritance occurs when a class is derived from another derived class, extending inheritance through multiple layers. For example, `Child` inherits from `Parent`, which inherits from `Grandparent`, making `Child` the subclass of `Parent` and `Grandparent`, as shown in . In multiple inheritance, a class may inherit from more than one class. The `Child` class inherits from `Parent1` and `Parent2`, showcasing how it can access methods from both parent classes, as demonstrated in .

In object-oriented programming, constructors are special methods executed when a new instance of a class is created, used to initialize the instance's attributes. In the `Car` class, the constructor `__init__` initializes the `brand` attribute and prints a message indicating that the car has been created, as shown in . Destructors, defined by `__del__`, are used for any necessary cleanup when an instance is destroyed. Though Python handles garbage collection automatically, explicit destructors can be used for resource cleanup, as observed with the `Car destroyed` print statement when an instance is deleted .

Regular expressions can be used to match specific patterns in text, making them a powerful tool for finding and validating email addresses. In the sources, a regular expression pattern is defined as `r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'`. This pattern matches the typical structure of an email address, capturing characters before and after an `@` symbol and ensuring there is a proper domain format including a dot. The function `validate_email` uses this pattern to confirm if a given string adheres to common email format requirements .

Thread synchronization using locks in Python ensures that shared resources are not modified by multiple threads at the same time, preventing race conditions and data inconsistency. A lock provides mutual exclusion: only one thread can acquire the lock and access the critical section of code at a time. For example, the `balance` variable in a multithreading scenario needs locking to avoid simultaneous modifications that lead to incorrect results. Utilizing lock mechanisms properly is crucial in maintaining data integrity in multithreaded programs, as demonstrated in various threading examples from the sources .

In Python, method overriding occurs when a child class provides a specific implementation of a method that is already defined in its parent class. When the method called is defined in the child class, the child class's method is executed instead of the parent's method, despite the method name being the same. This allows the child class to modify behavior as needed. In the provided source, the class `Child` overrides the `show` method of the `Parent` class. Calling `c.show()` on an instance `c` of `Child` results in the overridden method in `Child` being executed, as seen in .

Encapsulation in object-oriented programming implies bundling data with methods that operate on that data, restricting direct access to some of the object's components. The `BankDemo` class encapsulates operations related to a bank account, such as depositing and withdrawing, ensuring that the account balance is managed internally and accessed or modified only through designated methods. This promotes data integrity and security by controlling how data is accessed and modified. However, improper encapsulation or inadequate access controls can still leave systems prone to misuse or errors, as can be scenario-specific .

The `@staticmethod` decorator in Python allows methods to be called on a class without requiring an instance of the class. Static methods do not access or modify class state and parameters like `self` or `cls` are not accessible. In the `Math` class, `add` and `multiply` are static methods that perform operations on provided arguments directly, which means they can be called as `Math.add(...)` or `Math.multiply(...)` without instantiating `Math`, demonstrating the use of static methods for utility functions that require neither instance state nor class modifications .

Class attributes are shared among all instances of a class, meaning that if a class attribute is changed, it affects all instances of that class. Instance attributes are specific to each instance of a class, meaning that changes to these attributes only affect the particular instance. In the source, the `Car` class has a class attribute `wheels` with a value of 4, shared across all instances. In contrast, attributes `brand` and `color` are instance attributes, specific to each car instance .

Composition in Python involves assembling classes by including instances of other classes, allowing functionality to be delegated to these components. In the `Computer` class, composition is used to include a `Printer` object as a part of its internal structure. The `print_document` method of `Computer` delegates the task of printing to the `Printer` class's `print_page` method. This form of composition allows `Computer` to use `Printer`’s functionality as a component, illustrating a has-a relationship rather than an is-a, which is typical for inheritance .

Operator overloading in Python allows developers to specify the behavior of operators for user-defined types. In the `Number` class, the `__add__` method is defined to overload the `+` operator, enabling addition of two `Number` instances by summing their `value` attributes. When `n1 + n2` is executed, Python internally calls `n1.__add__(n2)`, resulting in the output of their sum, which is not the standard behavior of adding numbers by their default data types .

You might also like