0% found this document useful (0 votes)
2 views

Lab9

This document is a lab handout for a course on Object Oriented Programming, focusing on the implementation and comparison of static methods, class methods, and instance methods in Python. It provides definitions, syntax, and examples for each method type, highlighting their differences and appropriate usage. Additionally, it includes tasks for students to practice writing Python programs using these methods.

Uploaded by

thewriterdeenan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab9

This document is a lab handout for a course on Object Oriented Programming, focusing on the implementation and comparison of static methods, class methods, and instance methods in Python. It provides definitions, syntax, and examples for each method type, highlighting their differences and appropriate usage. Additionally, it includes tasks for students to practice writing Python programs using these methods.

Uploaded by

thewriterdeenan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Institute of Biomedical Engineering and Technology

Liaquat University of Medical and Health Sciences Jamshoro, Sindh.

Subject: Object Oriented Programming Year: 1st, Semester: 2nd


Lab Handout-09

Name: ________________________________ Roll No: ________________________

Date: _________________ Signature of Tutor: __________________

To understand Static and Class Methods in Python

Objective:
• Implement static and class methods within a class in Python.
• Compare the usage of static and class methods with instance methods.

Introduction:

class MyClass:
def method(self):
return 'instance method called', self

@classmethod
def classmethod(cls):
return 'class method called', cls

@staticmethod
def staticmethod():
return 'static method called'

Instance Method (method):


The method is a typical instance method, taking self as its first parameter. It operates on an
instance of the class and can access and modify instance-specific data.

Class Method (classmethod):


The classmethod decorator is used to define a class method. It takes cls as its first parameter,
representing the class itself. Class methods can access and modify class-specific data.

Static Method (staticmethod):


The static method decorator is used to define a static method. Unlike instance and class
methods, it does not take the instance or class as its first parameter. It is independent of the
instance and class and operates on general data.

Class Method: Class methods are the type of method used when a method is not really about
an instance of a class, but the class itself. To create a class method, just add '@classmethod'
a line before creating the class method. The class is automatically the first argument to be
passed in, and is represented as 'cls' instead of 'class'. This is because 'class' is already
assigned to be something else in Python.
Syntax Python Class Method:
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):

• A class method is a method that is bound to the class and not the object of the class.
• They have the access to the state of the class as it takes a class parameter that points to
the class and not the object instance.
• It can modify a class state that would apply across all the instances of the class. For
example, it can modify a class variable that will be applicable to all the instances

Static Method: A static method does not receive an implicit first argument. A static method is
also a method that is bound to the class and not the object of the class. This method can’t
access or modify the class state. It is present in a class because it makes sense for the method
to be present in class.
class C(object):
@staticmethod
def fun(arg1, arg2, ...):
Static methods are different from regular methods and class methods in that it doesn't have a
class or instance that is automatically passed in as a first positional argument. They can be
created by adding '@staticmethod' a line before defining the method. These are methods that
have a logical connection to the Class, but does not need a class or instance as an argument. It
is better to make sure we create a static method rather than class or regular method when we
are sure that we don't make use of the class or instance within the method.

Class method vs Static Method


The difference between the Class method and the static method is:
• A class method takes cls as the first parameter while a static method needs no specific
parameters.
• A class method can access or modify the class state while a static method can’t access
or modify it.
• In general, static methods know nothing about the class state. They are utility-type
methods that take some parameters and work upon those parameters. On the other
hand class methods must have class as a parameter.
• We use @classmethod decorator in python to create a class method and we use
@staticmethod decorator to create a static method in python.
Example:
class MyClass:
def __init__(self, value):
self.value = value

@staticmethod
def get_max_value(x, y):
return max(x, y)

# Create an instance of MyClass


obj = MyClass(10)

# Call the static method using the class name


print(MyClass.get_max_value(20, 30))

# Call the static method using an instance of MyClass


print(obj.get_max_value(20, 30))

Explanation:
MyClass has a constructor (__init__) that initializes an instance variable value.
It also has a static method (get_max_value) that takes two parameters (x and y) and returns
the maximum of the two values using the max function.
An instance of MyClass is created with obj = MyClass(10).
The static method get_max_value is called using the class name
MyClass.get_max_value(20, 30). It returns the maximum of 20 and 30, which is 30.
The static method is also called using an instance obj.get_max_value(20, 30). This is a valid
way to call a static method, but it is generally recommended to call static methods using the
class name.
Example:
from datetime import date

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

# Class method to create a Person object by birth year.


@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)

# Static method to check if a Person is adult or not.


@staticmethod
def isAdult(age):
return age > 18

# Create instances of Person class


person1 = Person('Sandy', 21)
person2 = Person.fromBirthYear('Butterworth', 1996)

# Print the names & ages of the persons


print(person1.name, person1.age)
print(person2.name, person2.age)

# Check if a person is adult using the static method


print(Person.isAdult(22))
Example

class MathOperations:
pi = 3.14159 # Class variable

def __init__(self, radius):


self.radius = radius

# Instance method to calculate the area of a circle


def calculate_area(self):
return self.pi * self.radius**2

# Class method to provide information about the constant pi


@classmethod
def get_pi_info(cls):
return f"The value of pi is approximately {cls.pi}."

# Static method to check if a number is even


@staticmethod
def is_even(number):
return number % 2 == 0

# Usage of the class


radius_value = 5
circle_instance = MathOperations(radius_value)

# Calling instance method to calculate area


area = circle_instance.calculate_area()
print(f"The area of the circle with radius {radius_value} is: {area}")

# Calling class method to get information about pi


pi_info = MathOperations.get_pi_info()
print(pi_info)

# Calling static method to check if a number is even


number_to_check = 10
is_even_result = MathOperations.is_even(number_to_check)
print(f"Is {number_to_check} an even number? {is_even_result}")
Example

class StringUtils:
@staticmethod
def is_palindrome(word):
cleaned_word = ''.join(char.lower() for char in word if char.isalnum())
return cleaned_word == cleaned_word[::-1]

@classmethod
def count_vowels(cls, text):
vowels = 'aeiou'
return sum(1 for char in text.lower() if char in vowels)

# Usage of the class methods


word_to_check = "level"
is_palindrome_result = StringUtils.is_palindrome(word_to_check)
print(f"Is '{word_to_check}' a palindrome? {is_palindrome_result}")

text_to_count_vowels = "Hello, how are you?"


vowel_count = StringUtils.count_vowels(text_to_count_vowels)
print(f"The number of vowels in '{text_to_count_vowels}' is: {vowel_count}")

Explanation:
char.isalnum()
• This checks if each character (char) in the input string (word) is an alphanumeric
character (a letter or a digit).
char.lower()
• This converts each character to its lowercase form. This is done to make the
comparison case-insensitive.
''.join(...)
• This joins the characters that satisfy the conditions (alphanumeric) into a new string.
cleaned_word
• is a string that contains only alphanumeric characters in lowercase.
cleaned_word[::-1]
• This creates a reversed version of cleaned_word using slicing.
Task:
1. Write a python program using static and class methods.

You might also like