python class string representation code example
Example 1: string representation of object python
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)
Example 2: <__main__.boat object at 0x7fc678e66cd0> even after using __str__
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)