Saturday, 5 December 2015

Python: __str__(): Print object using print method


If you define __str__() method in your class, python print method display the value returned by __str__() method.
class Employee:
    def __init__(self, firstName, lastName):
        self.firstName=firstName
        self.lastName=lastName

    def __str__(self):
        return self.firstName+" " +self.lastName

if __name__=="__main__":
    emp1=Employee("Hari Krihsna", "Gurram")
    print(emp1)

Output
Hari Krihsna Gurram



Previous                                                 Next                                                 Home

No comments:

Post a Comment