Defining a String Representation
Python |
Java |
The str function converts any object to its string representation. Example: str(3.14) # returns
'3.14' This function can be
customized to return the appropriate string for objects of any programmer-defined
class by including an __str__ method. When the __str__ method is available, operations such as print automatically use it to obtain an objectÕs string representation. Example: class Student: NUM_GRADES = 5 def __init__(self, name): self.name = name
self.grades = []
for i in range(Student.NUM_GRADES):
self.grades.append(0) def __str__(self):
"""Format: Name on the first line
and all grades on the second line,
separated by spaces.
"""
result = self.name + '\n'
result += ''.join(map(str, self.grades))
return result Usage: s1 =
Student('Mary') print(s1)
s2 = Student('Bill') print(str(s1) +
'\n' + str(s2))
|
The toString() method returns the string representation of an
object. A default implementation
of this method is included in the Object class.
This implementation returns a string containing the name of the
objectÕs class and its hash code.
Thus, if the programmer does not include toString in a given class, the default is used via
inheritance (Object is the ancestor class of all objects). Operations such as println and + automatically call toString with objects to obtain their string
representations. The header of toString is public String
toString() Example: public class
Student{ public static final int
NUM_GRADES = 5; private String name; private int[] grades; public Student(String
name){
this.name = name;
this.grades = new int[NUM_GRADES]; } public String toString(){
/*
Format: Name on the first line
and all grades on the second line,
separated by spaces.
*/
String result = this.name + '\n';
for (String grade : this.grades)
result += grade + ' ';
return result; } } Usage: s1 = new
Student("Mary"); System.out.println(s1); s2 = new
Student("Bill"); System.out.println(s1
+ '\n' + s2); |