[英]How to implement string in python class?
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 的文件:
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.我知道我需要实现一个字符串,但我被卡住了。
You need to define the __str__
method in your employee class.您需要在您的员工 class 中定义
__str__
方法。 This tells the compiler how to output your class as a string instead of the object hash.这告诉编译器如何将 output 您的 class 作为字符串而不是 object Z0800FC577294C34E0B28AD283
class Employee:
def __str__(self):
return f"{self.__empName}, {self.__idNumber}, {self.__department}, {self.__title}"
The double underscore you're using in your class usually denotes that it's a private variable/attribute.您在 class 中使用的双下划线通常表示它是私有变量/属性。 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.如果您想在 class 之外调用这些属性,那么它们是公共的还是私有的,因此不需要双下划线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.