2015-08-28 112 views
0

在Python如果你想打印一类的属性的字符串表示你需要定义类似如何使用java打印对象名称的类的属性?

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是否有蟒蛇__str__的相同呢?如果不是我怎么能达到上面的输出?

+0

我猜你正在寻找[MessageFormat中(http://docs.oracle.com/javase/7/docs/api/java/相同text/MessageFormat.html)类,您可以在其中将动态值传递给'String' –

+0

它在java中被称为'toString()'。只是实现(它实际上是一个**重写**)'公共字符串toString(){返回“无论”;}'你会很好去.. – Codebender

+0

FWIW,你的'__str __()'方法是非常坏的。 –

回答

1

重写“toString()”。我认为这是与STR()在python

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()); 
} 
}