Home > other >  How to implement string in python class?
How to implement string in python class?

Time:12-15

I'm working on a problem called "Employee Class" and mostly thru it but it's not printing what I want. This is my program:

from EmployeeDefinition import *

def main():
   
    emplo1 = Employee('Susan Meyers', '47899',
                        'Accounting', 'Vice President')
    emplo2 = Employee('Mark Jones', '39119',
                        'IT', 'Programmer')
    emplo3 = Employee('Joy Rogers', '81774',
                        'Manufacturing', 'Engineer')

    print(f"Employee 1:{emplo1}\n")
    print(f"Employee 2:{emplo2}\n")
    print(f"Employee 3:{emplo3}\n")

if __name__ == '__main__':
    main()

and this is the file with my class in it:

class Employee:
    __empName = "-na-"
    __idNumber = '0'
    __department = "-na-"
    __title = "-na-"
    
    def __init__(self, inp_empName, inp_idNumber, inp_dept, inp_title):
        self.__empName = inp_empName
        self.__idNumber = inp_idNumber
        self.__department = inp_dept
        self.__title = inp_title

    def setEmpName(self, inp_empName):
        self.__empName = inp_empName

    def setIdNumber(self, inp_idNumber):
        self.__idNumber = inp_idNumber

    def setDepartment(self, inp_dept):
        self.__department = inp_dept

    def setTitle(self, inp_title):
        self.__title = inp_title
    
    def getEmpName(self):
        return self.__empName
        
    def getIdNumber(self):
        return self.__idNumber
        
    def getDepartment(self):
        return self.__department

    def getTitle(self):
        return self.__title

I know I need to implement a string but I'm stuck.

CodePudding user response:

You need to define the __str__ method in your employee class. This tells the compiler how to output your class as a string instead of the object hash.

class Employee:
    def __str__(self):
        return f"{self.__empName}, {self.__idNumber}, {self.__department}, {self.__title}"

CodePudding user response:

The double underscore you're using in your class usually denotes that it's a private variable/attribute. Example:

def __init__(self, inp_empName, inp_idNumber, inp_dept, inp_title):
        self.empName = inp_empName
        self.idNumber = inp_idNumber
        self.department = inp_dept
        self.title = inp_title

If you simply remove those underscores, you can call the string like this:

print(f"Employee 1:{emplo1.empName}\n")

If you want to call those attributes outside of the class, then they're public versus private, so the double underscore is unnecessary.

  • Related