Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python __str__ vs __repr__

class Person:

    def __init__(self, person_name, person_age):
        self.name = person_name
        self.age = person_age

    def __str__(self):
        return f'Person name is {self.name} and age is {self.age}'

    def __repr__(self):
        return f'Person(name={self.name}, age={self.age})'


p = Person('Pankaj', 34)

print(p.__str__())
print(p.__repr__())
Output:

Person name is Pankaj and age is 34
Person(name=Pankaj, age=34)
Comment

When To Use __repr__ vs __str__?

# When To Use __repr__ vs __str__?
# Emulate what the std lib does:

import datetime
today = datetime.date.today()

# Result of __str__ should be readable:

print(str(today))

# Output
# '2017-02-02'

# Result of __repr__ should be unambiguous:

print(repr(today))

# Output
# 'datetime.date(2017, 2, 2)'

# Python interpreter sessions use 
# __repr__ to inspect objects:

print(today)

# Output
# datetime.date(2017, 2, 2)
Comment

PREVIOUS NEXT
Code Example
Python :: paradigm meaning in python 
Python :: python try and except 
Python :: Iterate through string backwards in python 
Python :: python flask how to remove last character from string 
Python :: how to select top 5 in every group pandas 
Python :: how to make a terminal in python 
Python :: download image from url python requests 
Python :: how to check any script is running in background linux using python 
Python :: how to calculate the variance of all columns in python 
Python :: modify a list with for loop and range function in python 
Python :: CSV data source does not support array<string data type 
Python :: python mathematics 
Python :: pandas convert string column to int list column 
Python :: how to make a dict from a file py 
Python :: how to extract field values in list from queryset in django 
Python :: max of double array python 
Python :: file uploads django 
Python :: find element in list that matches a condition 
Python :: aws django migrate 
Python :: Invalid password format or unknown hashing algorithm. 
Python :: fibonacci number 
Python :: python list directories only 
Python :: concatenate string and int python 
Python :: not in python 
Python :: virtual environments for python 
Python :: I have string index in pandas DataFrame how can I select by startswith? 
Python :: timedelta python days 
Python :: detailview 
Python :: python runserver port 
Python :: django signals post_save not working 
ADD CONTENT
Topic
Content
Source link
Name
4+9 =