我在jupyter笔记本和googlecolab上学习python编程课程
我不明白这门课的结果
class employee_constructor():
def __init__(self,name,surname,salary):
self.name=name
self.surname=surname
self.salary=salary
def increasesalary(self,percentage):
self.salary=self.salary*(1+percentage/100)
def displayEmployee(self):
print('this employee is {} and gets {} dollars'.format(emp1.name,emp1.salary))
现在我试着打印结果:
emp1=employee_constructor('jose','ferro',1000)
emp2=employee_constructor('manolo','rod','1500')
emp1.displayEmployee
print('before increase',emp1.salary)
emp1.increasesalary(5)
emp1.increasesalary(5)
print('after increase',emp1.salary)
print(emp1.salary)
# this line does not give error and does nothing:
emp1.increasesalary
print(emp1.salary)
# this line gives error:
# increasesalary() missing 1 required positional argument: 'percentage'
emp1.increasesalary()
我不明白为什么不带括号运行方法不会导致任何错误(实际上方法没有运行),而带括号运行方法(不通过错误传递必要的变量)
第二,我怎样才能避免这样的错误呢?i、 e.如果用户未通过任何测试,则假定值为零
注: this question解释了init方法,并作为解决方案提出。我的问题是相关的,但没有得到回答
当您通过
object.method
引用方法(对象上下文中的函数,self
被隐式传递)时,将返回method对象。但要真正执行这个函数,你需要调用它,即使用括号有趣的是,将返回的method对象保存为一个变量并调用它,您将看到它们引用同一个对象时执行的操作是相同的
现在,调用
emp1.increasesalary()
时,没有传递所需的参数percentage
,从而导致错误。再次注意,self
(对象本身)是隐式传递的使参数成为默认值为0的关键字参数:
在python中始终可以使用函数(不带括号):
这不会调用函数,而只是打印出它的内存位置。因此,包含函数
f
本身的行是有效的python语句;但它不调用函数然后:您需要在
displayEmployee(self)
方法中使用self
而不是emp1
:更好:
那你就可以了
相关问题 更多 >
编程相关推荐