我正在使用Spyder完成Python作业,但代码似乎将dailyEffort方法误认为是对象属性。这是我的密码:
class Student:
def __init__(self,name,ID,dept=None):
self.name=name
self.ID=ID
if dept==None:
self.dept="CSE"
elif dept!=None:
self.dept=dept
self.sugg=""
self.dE=0
def dailyEffort(self,hour): #Clearly this is a method
self.hour=hour
self.dE+=self.hour
if self.hour<=2:
self.sugg="Should give more effort!"
elif self.hour<=4:
self.sugg="Keep up the good work!"
else:
self.sugg="Excellent! Now motivate others."
def printDetails(self):
print("Name: ",self.name)
print("ID: ",self.ID)
print("Department: ",self.dept)
print("Daily Effort: ",self.dE," hour(s)") #I'm not even calling that method over here
print("Suggestion: ",self.sugg)
bob = Student('Bob', 123)
bob.dailyEffort(3) #This is where the code mistakes dailyEffort as an attribute
bob.printDetails()
print('========================')
alice = Student("Alice", 456, "BBA")
alice.dailyEffort(2)
alice.printDetails()
print('========================')
carol = Student("Carol", 777, "MAT")
carol.dailyEffort(6)
carol.printDetails()
以下是我得到的输出:
runfile('C:/Users/USER/.spyder-py3/temp.py', wdir='C:/Users/USER/.spyder-py3')
Traceback (most recent call last):
File "C:\Users\USER\.spyder-py3\temp.py", line 27, in <module>
bob.dailyEffort(3)
AttributeError: 'Student' object has no attribute 'dailyEffort'
以下是所需的输出:
Name: Bob
ID: 123
Department: CSE
Daily Effort: 3 hour(s)
Suggestion: Keep up the good work!
========================
Name: Alice
ID: 456
Department: BBA
Daily Effort: 2 hour(s)
Suggestion: Should give more effort!
========================
Name: Carol
ID: 777
Department: MAT
Daily Effort: 6 hour(s)
Suggestion: Excellent! Now motivate others.
请建议我尽量少做改动
简单的缩进问题
输出:
def
创建函数。如果一个函数是在类范围内定义的,并且在类的实例上调用它,python将把它作为类方法进行特殊处理。如果一个函数是在另一个函数中创建的,它将不是一个方法,但是如果它在包含函数中使用变量,它将是一个闭包在您的例子中,
dailyEffort
是在__init__
函数中定义的,但它不使用任何包含变量,因此它只是一个常规函数对象,其名称仅在__init__
函数的局部已知Dedent与
def __init__(...)
的级别相同,它将作为一种方法工作您的代码完全正确,只是缩进错误
实际输出:
相关问题 更多 >
编程相关推荐