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

PYTHON PROGRAMMING 1

This document provides an overview of printing objects in Python, focusing on the use of __str__ and __repr__ methods to display object information. It includes examples demonstrating how to define classes and implement these methods for formatted output. Additionally, it covers advanced formatting techniques and the print function's parameters for effective debugging and information dissemination.

Uploaded by

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

PYTHON PROGRAMMING 1

This document provides an overview of printing objects in Python, focusing on the use of __str__ and __repr__ methods to display object information. It includes examples demonstrating how to define classes and implement these methods for formatted output. Additionally, it covers advanced formatting techniques and the print function's parameters for effective debugging and information dissemination.

Uploaded by

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

MODULE 5

CLASSES AND OBJECTS


INTRODUCTION TO PYTHON PROGRAMMING
BPLCK205B
TOPIC :
1.PRINTING OBJECTS AND MORE COMPLICATED
EXAMPLE
1 . PRINT
OBJECTS

• AN OBJECT IS THE PART OF THE OBJECT ORIENTED


PROGRAMMING (OOPS), WHICH IS AN INSTANCE OF THE CLASS.
THE CLASS IS THE BLUEPRINT OR TEMPLATE THAT SPECIFIES
THE METHODS AND PROPERTIES OF THAT GIVEN CLASS. WHEN
WE CREATE AN OBJECT OF A CLASS, IT CONTAINS ALL THE SET
OF INSTANCE METHODS AND VARIABLES THAT ARE RELATED TO
THAT PARTICULAR OBJECT .
USING __STR__ METHOD

•WE HAVE TWO METHODS NAMELY, DEF __STR__(SELF):


__STR__ OR __REPR__ IN PYTHON WHICH RETURN
AUTOMATICALLY CALLS THE STRING STRING_REPRESENTATION
AND USED TO PRINT THE OBJECT WITH PRINT(OBJECT_NAME(INPUTS)
THE DETAIL VIEW ABOUT IT. FOLLOWING
IS THE SYNTAX FOR USING THE __STR__
DEF __REPR__(SELF):
METHOD.
RETURN
STRING_REPRESENTATION
PRINT(OBJECT_NAME(INPUTS)
EXAMPLE 1.
IN THE FOLLOWING EXAMPLE, WE ARE CREATING A CLASS AND
AN OBJECT USING PYTHON; AND IN THE CLASS WE WILL DEFINE
THE FUNCTION ALONG WITH THE __STR__ METHOD BY GIVING THE
FORMATTED TEXT IN IT AND FINALLY PRINTS THE OBJECT.
CLASS PERSON:

DEF __INIT__(SELF, NAME, AGE, GENDER):

SELF.NAME = NAME

SELF.AGE = AGE

SELF.GENDER = GENDER

DEF __STR__(SELF):

RETURN MY NAME IS {SELF.NAME} AND I AM


• OUTPUT
{SELF.AGE} YEARS OLD."
• MY NAME IS JOHN AND I AM 30 YEARS OLD.
PERSON1 = PERSON("JOHN", 30, "MALE")
• MY NAME IS JANE AND I AM 25 YEARS OLD.
PERSON2 = PERSON("JANE", 25, "FEMALE")

PRINT(PERSON1)

PRINT(PERSON2)
EXAMPLE 2.
IN THE FOLLOWING EXAMPLE, IF WE OMIT MENTIONING THE METHOD, THEN THE
DESCRIPTION OF THE OBJECT WILL BE PRINTED RATHER THAN THE DATA OF THE
OBJECT.

• CLASS PERSON:

• DEF __INIT__(SELF, LANGUAGE, STATE, • OUTPUT


GENDER):
• <__MAIN__.PERSON OBJECT
• SELF.NAME = LANGUAGE
AT 0X0000029D0DAD7250>
• SELF.AGE = STATE

• SELF.GENDER = GENDER

• • <__MAIN__.PERSON OBJECT
• PERSON1 = PERSON("JOHN", 30, "MALE") AT 0X0000029D0DBEF7F0>
• PERSON2 = PERSON("JANE", 25, "FEMALE")

• PRINT(PERSON1)

• PRINT(PERSON2)
EXAMPLE 3.
IN PYTHON WE HAVE ANOTHER METHOD NAMED __REPR__ TO PRINT THE
OBJECT WITH THE DETAILED VIEW. THIS METHOD IS AS SAME AS THE __STR__
METHOD BUT THE DIFFERENCE IS THAT, IT HANDLES MORE DETAILS OF THE
OBJECT.
• CLASS PERSON:

• DEF __INIT__(SELF, NAME, STATE, PLACE):

• SELF.NAME = NAME

• SELF.STATE = STATE
• OUTPUT
• SELF.PLACE = PLACE
• JOHN BELONGS TO ANDHRA
• DEF __REPR__(SELF):
PRADESH AND THE HOME
• RETURN F"{SELF.NAME} BELONGS TO {SELF.STATE}
TOWN OF JOHN IS
AND THE HOME TOWN OF {SELF.NAME} IS {SELF.PLACE}"
VISHAKHAPATNAM

• JANE BELONGS TO TELANGANA
• PERSON1 = PERSON("JOHN", "ANDHRA PRADESH", "MALE")
AND THE HOME TOWN OF JANE
• PERSON2 = PERSON("JANE", "TELANGANA", "FEMALE")
IS HYDERABAD .

• PRINT(PERSON1)

• PRINT(PERSON2)
EXAMPLE 4.
WHEN WE DIDN’T USE THE __REPR__ IN THE USER DEFINED CLASS AND IF WE
TRY TO PRINT THE OBJECT THEN THE OUTPUT OF THE PRINT STATEMENT WILL
BE THE DESCRIPTION OF THE OBJECT.

• CLASS PERSON:
• DEF __INIT__(SELF, NAME, STATE, GENDER):
• SELF.NAME = NAME
• OUTPUT

• SELF.STATE = STATE • <__MAIN__.PERSON


• SELF.GENDER = GENDER OBJECT AT
0X0000029D0DBE7790>

• PERSON1 = PERSON("JOHN", "ANDHRA • <__MAIN__.PERSON


PRADESH", "MALE") OBJECT AT
• PERSON2 = PERSON("JANE", "TELANGANA", 0X0000029D0DBE7CA0>
"FEMALE")

• PRINT(PERSON1)
• PRINT(PERSON2)
Printing objects give us information about the
objects we are working with. In C++, we can do
this by adding a friend ostream& operator <<
method for the class. In Java, we use toString()
method. In Python, this can be achieved by
using __repr__ or __str__ methods. __repr__ is
used if we need a detailed information for
debugging while __str__ is used to print a string
version for the users.
# PYTHON PROGRAM TO
DEMONSTRATE
# OBJECT PRINTING
# DEFINING A CLASS
CLASS TEST:
DEF __INIT__(SELF, A, B):
SELF.A = A
SELF.B = B

DEF __REPR__(SELF):

RETURN "TEST A:% S B:% S" %


(SELF.A, SELF.B)

• OUTPUT :
DEF __STR__(SELF):

RETURN "FROM STR METHOD OF • FROM STR METHOD OF TEST: A IS


TEST: A IS % S, " \ 1234, B IS 5678
"B IS % S" % (SELF.A, SELF.B)
• [TEST A:1234 B:5678]
# DRIVER CODE

T = TEST(1234, 5678)

# THIS CALLS __STR__()

PRINT(T)

# THIS CALLS __REPR__()


Important Points about Printing:

Python uses __repr__ method if there is no __str__


method.
Example:

class Test:
def __init__(self, a, b):
self.a = a
self.b = b

def __repr__(self):
return "Test a:% s b:% s" % (self.a, self.b)

# Driver Code
t = Test(1234, 5678)
print(t)

Output:

Test a:1234 b:5678


If no __repr__ method is defined then the default is used.
Example:

class Test:
def __init__(self, a, b):
self.a = a
self.b = b

# Driver Code
t = Test(1234, 5678)
print(t)

Output:

<__main__.Test object at 0x7f9b5738c550>


Understanding the Basics of Printing Objects
At its core, printing objects involves using the print() function.
This function allows you to display information on the console,
making it an essential part of your Python toolkit. You can print
strings, variables, numbers, and even complex data structures
like lists and dictionaries.

name = "Alice"
age = 30
print("Hello, my name is", name, "and I am", age, "years old.")

In this example, we use the print() function to output a string


with variables. Python automatically adds spaces between the
elements, resulting in a clean output.
Advanced Formatting Techniques
Now, let's say you want to show something more than just plain text. Maybe
you want to show the price of an item with two decimal places. Python has a
cool trick for that called f-strings. It's like creating a little template where you
can put different things.

item = "book"
price = 25.99
print(f"The {item} costs ${price:.2f}.")

Here, we used an f-string to create a sentence. The {} braces act like


placeholders, and the :.2f inside them means "show the number with two
decimal places." When you run this code, Python will fill in the placeholders
with the values of the item and price, and it will show you the sentence with the
correct price.
Let's say you made your own type of thing, like a Book:

class Book:
def __init__(self, title, author):
self.title = title
self.author = author
book = Book("The Python Guide", "John Smith")
print(book)

In this code, we defined a Book class. Think of it as a


blueprint for creating books. We made a book called
"The Python Guide" by "John Smith." When we print the
book object, Python shows us the details we specified.
print() Parameters :

*objects – indicates one or more values/objects to be


printed. It is converted to string before printing.

sep (Optional) – this specifies how objects should be


separated if multiple objects are passed. Default value: ‘ ‘

end (Optional) – specifies what is to be printed at last.


Default value: \n

file (Optional) – object with a write(string) method. Default


value: sys.stdout

flush (Optional) – A Boolean indicating whether if the


stream/output is flushed (True) or buffered (False). Default
value: False

Note – The sep, end, file, and flush parameters are


keyword arguments. If we want to use them in the
function, we need to specify their keywords compulsorily.
For example:
# Python program to illustrate print()
print(12.35)

print('Python Programming')

print(True)

print(1 + 5j)

my_list = [1, 2, 3, 4]
print(my_list)

my_dict = {1: 'One', 2: 'Two', 3: 'Three'}


print(my_dict)

Output :
12.35
Python Programming
True
(1+5j)
[1, 2, 3, 4]
{1: 'One', 2: 'Two', 3: 'Three'}
Consider a scenario involving a custom-made Person class:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
print(f"Person's name: {person.name}")
print(f"Person's age: {person.age}")

Here, the print statements cast a radiant light on the attributes of the
person object. As you execute the code, a clear snapshot of the object's
inner state is unveiled, helping you pinpoint any discrepancies or issues.
Conclusion :

Mastering the art of printing objects in


Python is a vital skill for effective
debugging and information
dissemination. From basic print
statements to advanced formatting
techniques and logging, you've
explored various strategies to
enhance your code understanding.

By leveraging these tools, you're


equipped to tackle complex
debugging scenarios, gain insights
into data structures, and create more
informative and efficient code.
THANK YOU !!

You might also like