首页 > 解决方案 > 没有从前一个函数传递变量

问题描述

进行赋值并且无法在同一类中的两个方法之间传递变量。

global check
wage = 0
hours = 0
check = 0


class employee:
  def __init__(self, name, wage, hours, check):
    self.name = name
    self.wage = wage
    self.hours = hours
    self.check = check

  def paycheck(self):
    if self.hours > 41:
      self.hours = self.hours - 40
      overtime = self.wage * self.hours * 1.5
      self.check = (40 * self.wage) + overtime
      return self.check
      #print(self.check)
    else:
      self.check = self.hours * self.wage
      return self.check
      #print(self.check)
    
  def __str__(self):
    return self.name + ":\n Net Pay: $" + str(self.check)



A_emp = employee("Alice", 20, 40, 0)
B_emp = employee("Bob", 15, 50, 0)

print(A_emp)
print(B_emp)

输出应显示每个员工的“净工资”,并显示大部分str方法:

Alice:
 Net Pay: $0
Bob:
 Net Pay: $0

但是,检查变量只是不会在类方法之间传递值。我已经将它全球化,在课堂之外定义它,并尝试了self.checkcheck的不同变体。感觉就像我只是在扔东西,没有任何东西粘在上面。谢谢你的帮助。

标签: pythonpython-3.x

解决方案


您忘记调用 paycheck() 方法。还要摆脱你的全局变量和返回语句。

class employee:
    def __init__(self, name, wage, hours, check):
        self.name = name
        self.wage = wage
        self.hours = hours
        self.check = check

    def paycheck(self):
        if self.hours > 41:
            self.hours = self.hours - 40
            overtime = self.wage * self.hours * 1.5
            self.check = (40 * self.wage) + overtime

        else:
            self.check = self.hours * self.wage

    def __str__(self):
        return self.name + ":\n Net Pay: $" + str(self.check)


A_emp = employee("Alice", 20, 40, 0)
B_emp = employee("Bob", 15, 50, 0)

A_emp.paycheck()
B_emp.paycheck()

print(A_emp)
print(B_emp)

输出:

Alice:
 Net Pay: $800
Bob:
 Net Pay: $825.0

推荐阅读