在Python中,如果要打印类属性的字符串表示,则可以定义类似
的内容。class building:
def __init__(self,type,height):
self.type = type
self.height = height
def __str__():
return "i am a %s and i am {:%.1f} meters tall", (type,height)
hospital = Building()
hospital.type = "Medical Facility"
hospital.height = 30
print(hospital)
>>> i am a Medical Facility and i am 30.0 meters tall
java是否具有python __str__
的等价物?如果不是,我怎样才能实现上面的输出?
答案 0 :(得分:1)
覆盖“toString()”。我认为它与python中的 str()相同
public class Employee {
public int id;
public String fName;
public String mName;
public Employee(int id, String fName, String mName) {
this.id = id;
this.fName = fName;
this.mName = mName;
}
@Override
public String toString() {
String output = "Hello, I am employee " + id + ", my first name is " + fName + " and my middle name is " + mName;
return output;
}
public static void main(String[] args) {
Employee e= new Employee(1, "foo" ,"bar");
System.out.println(e.toString());
}
}