2015-08-28 115 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()); 
} 
}