python - 没有从前一个函数传递变量
问题描述
进行赋值并且无法在同一类中的两个方法之间传递变量。
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.check与check的不同变体。感觉就像我只是在扔东西,没有任何东西粘在上面。谢谢你的帮助。
解决方案
您忘记调用 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
推荐阅读
- javascript - 我应该将对象作为函数的参数传递吗?
- java - 从 Jboss EAP 6.4 迁移到 WildFly 21
- python - Flask Python 未加载 main.css
- jenkins - Jenkins MultiBranch 管道,带有发往任何分支和特定分支的拉取请求
- visual-c++ - 最新的 Visual Studio 2019 v 16.10.0 和 _DEPRECATE_TR1_NAMESPACE
- c# - 如何在 C# [Open Invoice] 中发布具有两种不同文档类型和 HMAC 签名的 Multipart/mixed:boundary=”MIME-Boundary”
- arrays - Json 中的访问响应
- swift - 将 Objc 项目迁移到 Swift 时未定义的符号:_OBJC_CLASS_$_XXXX
- python - Pandas 按两列分组后对一列进行排序
- node.js - 使用节点实时更新