为类创建实例,并在Python3中调用方法(和打印结果)

2024-03-28 14:17:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我认为(希望)这没什么太严重的。我对Python是一个完全的n00b,虽然我一个人走了这么远,但我不知道下一步该去哪里。我基本上是在寻求:

Enter your name: Gerbil Fingerbottom
Enter your salary: 60000
How many years did you work? 25
Your monthly pension payout is $2,250.00

这是我刚刚写的代码,但由于我们只是学习类,我还是有点害怕。欢迎任何建议…解释是黄金。你知道吗


employee_name = ''
yearly_salary = []
service = []
class Employee:
    def __init__(self, emp_name, salary, yrs):
        self.employee_name = emp_name
        self.yearly_salary = salary
        self.service = yrs

    def Pension(self):
        pen_total = int(input(yearly_salary * service * .0015))
        return(pen_total)

name_in = input("Please enter a name: ")
salary_in = input("Please enter salary: ")
years_in = input("Please enter years of service: ")

Tags: nameinselfinputyourdefserviceemployee
2条回答

Pension中的input没有任何意义。您应该将数值属性强制转换为适当的类型(可能是int)。养老金本身也可能只是一个在__init__中计算一次的属性

class Employee:
    def __init__(self, emp_name, salary, yrs):
        self.name = emp_name 
        #You know it's an employee, no need to have that in the attribute name too
        self.yearly_salary = int(salary)
        self.service = int(yrs)
        self.pension = yearly_salary * service * .0015

然后构建Employee与任何其他对象相同的对象:

e = Employee(name_in, salary_in, service_in)
print('Your pension is: {}'.format(e.pension))

创建Employee类:

class Employee:
    def __init__(self, name, salary, yrs):
        self.name = name
        self.yearly_salary = int(salary)
        self.service = int(yrs)

    def Pension(self):
        pen_total = int(self.yearly_salary * self.service * .0015)   # Use self to access the attributes and methods of the class
        return pen_total

获取员工详细信息:

name_in = input("Please enter a name: ")
salary_in = input("Please enter salary: ")
years_in = input("Please enter years of service: ")

实例化类:

emp = Employee(name_in, salary_in, years_in)

打印养老金:

print('Your monthly pension payout is ${}'.format(emp.Pension()))

相关问题 更多 >