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

时间:2017-11-22 02:14:09

标签: python function class object

我认为(希望)这不是太严重。我用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: ")

2 个答案:

答案 0 :(得分:0)

input中的Pension没有任何意义。您应该将数字属性转换为适当的类型(对于所有内容可能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))

答案 1 :(得分:0)

创建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()))