Answers for "__repr__ python example"

3

python __repr__

class Person:
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

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

    def __str__(self):
        return 'Person(name='+self.name+', age='+str(self.age)+ ')'
Posted by: Guest on March-08-2020
6

python repr

# The repr() function returns a printable representational string of the given object.
>>> var = 'foo'
>>> print(repr(var))
"'foo'"
Posted by: Guest on March-26-2020
2

repr python

"""str() is used for creating output for end user while repr() is mainly used for debugging and development.
repr’s goal is to be unambiguous and str’s is to be readable.
For example, if we suspect a float has a small rounding error, repr will show us while str may not."""

import datetime
today = datetime.datetime.now() 
# Prints readable format for date-time object
print (str(today))
  
# prints the official format of date-time object
print (repr(today))  

Output:

2016-02-22 19:32:04.078030
datetime.datetime(2016, 2, 22, 19, 32, 4, 78030)

From: geeksforgeeks.org
Posted by: Guest on April-04-2021
0

python __repr__

import datetime
now = datetime.datetime.now()
now.__str__()
#>>> '2020-12-27 22:28:00.324317'
now.__repr__()
#>>> 'datetime.datetime(2020, 12, 27, 22, 28, 0, 324317)'
Posted by: Guest on April-19-2021
0

<__main__.boat object at 0x7fc678e66cd0> even after using __str__

#!/bin/python3

import math
import os
import random
import re
import sys

class Car:
    def _init_(self,speed,unit):
        self.speed=speed
        self.unit=unit
    def __str__(self):
        return "Car with the maximum speed of {} {}".format(self.speed,self.unit)  

class Boat:
    def _init_(self,speed):
        self.speed=speed
    	def __str__(self):
        	return "Boat with the maximum speed of {} knots".format(self.speed)  
            
            
check the indentation of Boat class __str__() method, it should be as shown below.
  
class Boat:
    def _init_(self,speed):
        self.speed=speed
    def __str__(self):
        return "Boat with the maximum speed of {} knots".format(self.speed)
Posted by: Guest on November-19-2020
0

python __repr__ meaning

>>>repr(y)
"'a string'"
>>>y2=eval(repr(y))
>>>y==y2
True
Posted by: Guest on April-06-2020

Python Answers by Framework

Browse Popular Code Answers by Language