我在这里创建了一个模块。
class Employee:
def __init__(self):
self.name = input("Enter your name: ")
self.account_number = int(input("Enter your account number: "))
def withdraw(self): # it receives values from for
if withdraw1 > current_balance:
print ("You have entered a wrong number: ")
else:
print ("The current balance is: ", current_balance - withdraw1)
import TASK2 # I am importing the module I created
c = TASK2.Employee()
def for(self):
c.withdraw1 = int(input("enter number: "))
c.current_balance = int(input("Enter the current balance: "))
d = method(c.withdraw) # here I am trying to pass the values to withdraw
print (d)
我得到的问题是,尽管它要求输入值而不是给我答案,但它给我的答案是“无”。
答案 0 :(得分:2)
这是我对您的代码的看法。
# 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()
方法的评论不正确。
“它从中接收值”
更准确地说,将首先计算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)
另一个问题是常规命名。这是我在定义名为for
>>> def for(a): return a
SyntaxError: invalid syntax
同样, for
是Python中的关键字,请勿使用它来命名变量,函数或类。
使用self
时,情况不太严重(但我可以看到它使您感到困惑)。 self
更是类方法中使用的约定。但是for_employee
不是一个类方法。因此,按照惯例,该参数不应命名为self
。
(我发现代码是意大利式的,如果您通过将for_employee
方法移到类本身来重构代码,可能会有所帮助。然后使用{ {1}}。)