0% found this document useful (0 votes)
4 views2 pages

Python Class Examples: Constructors & Methods

The document provides examples of Python classes demonstrating constructors, destructors, and string manipulation methods. It includes examples for creating a student object, managing object lifecycle, converting strings to uppercase, counting words in a sentence, and reversing a string. Each example illustrates basic object-oriented programming concepts in Python.

Uploaded by

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

Python Class Examples: Constructors & Methods

The document provides examples of Python classes demonstrating constructors, destructors, and string manipulation methods. It includes examples for creating a student object, managing object lifecycle, converting strings to uppercase, counting words in a sentence, and reversing a string. Each example illustrates basic object-oriented programming concepts in Python.

Uploaded by

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

Example 1: Constructor

class Student:
def __init__(self, name):
[Link] = name

def show(self):
print("Student Name:", [Link])

s1 = Student("John")
[Link]()

Example 2: Destructor
class Sample:
def __init__(self):
print("Object created")

def __del__(self):
print("Object destroyed")

s = Sample()
del s

Example 3: String - Convert to Uppercase


class Word:
def __init__(self, text):
[Link] = text

def to_upper(self):
print([Link]())

w = Word("hello world")
w.to_upper()

Example 4: String - Count Words


class Sentence:
def __init__(self, line):
[Link] = line

def count_words(self):
words = [Link]()
print("Number of words:", len(words))

s = Sentence("Python is a powerful language")


s.count_words()

Example 5: String - Reverse a String


class Reverser:
def __init__(self, text):
[Link] = text

def reverse(self):
print("Reversed String:", [Link][::-1])
r = Reverser("simple")
[Link]()

You might also like