这是我对您的代码的看法。
# TASK2.py
class Employee:
def __init__(self):
self.name = input("Enter your name: ")
self.account_number = int(input("Enter your account number: "))
# make sure you initialise your member variables!
self.withdraw_val = 0 # withdraw1 is ambiguous, so I use withdraw_val instead
self.current_balance = 0
# receives values from for ### no it doesn't, right now, it GIVES values TO your "for" function
def withdraw(self):
if self.withdraw_val > self.current_balance: # remember to use "self." to
# access members within the class
print ("You have entered a wrong number: ")
else:
# again, remember "self."
print ("The current balance is: ", self.current_balance - self.withdraw_val)
# TASK2sub.py
import TASK2
c = TASK2.Employee()
def for_employee(employee): # (1) don't use "self" outside a class
# it's contextually unconventional
# (2) "for" is a keyword in Python, don't use it for naming
# variables/functions, it'll mess things up
employee.withdraw_val = int(input("Enter value to withdraw: "))
employee.current_balance = int(input("Enter the current balance: "))
return employee.withdraw_val # not entirely sure what you want to return
# but you should definitely return something
# if you're going to assign it to some variable
d = for_employee(c.withdraw()) # "for_employee" function needs a return statement
# ".withdraw()" method should also require a return statement
print(d)
注意:从现在开始,我将参考您的原始for功能for_employee。另请注意,我仍然对您要完成的工作感到困惑,并且很可能有一个更合适的名称。
由于您的原始for_employee函数没有返回任何内容,因此None默认情况下它会返回。(这解释了您看到的输出。)
我认为您误解了函数的一般工作方式。例如,
d = for_employee(c.withdraw())
print(d)
您对该.withdraw()方法的评论不准确。
“它从 for 接收值”
更准确地说,c.withdraw()将首先计算,然后将返回的任何内容for_employee作为参数传递给函数。该方法不是“从”接收值,而是withdraw“将值赋予”for_employee函数。
更合理的是
c.withdraw() # on a line by itself, since it doesn't return anything
d = for_employee(c) # pass the entire object, since you'll be using self.withdraw_val and whatnot
print(d)
另一个问题是传统命名。这是我在定义名为的函数时从 IDLE(使用 Python 3.7)得到的for
>>> def for(a): return a
SyntaxError: invalid syntax
同样,for是 Python 中的关键字,不要用它来命名变量、函数或类。
使用self,它不那么严重(但我可以看到它让你感到困惑)。self更像是类方法中使用的约定。但for_employee 不是类方法。所以按照惯例,参数不应该命名为self.
(我发现代码像意大利面条一样,如果您通过将for_employee方法移动到类本身来重构代码可能会受益。那么使用 . 就完全有意义了self。)