类职员打印方法

2024-10-02 10:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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方法,并作为解决方案提出。我的问题是相关的,但没有得到回答


Tags: 方法nameselfinitdef错误employeesurname
2条回答

I don't understand why running the method without the parenthesis would not cause any error (actually the method is not run) whereas with the parenthesis (and not passing the neccesary variable through an error)

当您通过object.method引用方法(对象上下文中的函数,self被隐式传递)时,将返回method对象。但要真正执行这个函数,你需要调用它,即使用括号

有趣的是,将返回的method对象保存为一个变量并调用它,您将看到它们引用同一个对象时执行的操作是相同的

现在,调用emp1.increasesalary()时,没有传递所需的参数percentage,从而导致错误。再次注意,self(对象本身)是隐式传递的

how can I avoid such kind of errors? i.e. if the user passes nothing assume vale zero

使参数成为默认值为0的关键字参数:

def increasesalary(self, percentage=0):
    self.salary = self.salary * (1 + percentage / 100)

在python中始终可以使用函数(不带括号):

def f():
    pass

print(f)

这不会调用函数,而只是打印出它的内存位置。因此,包含函数f本身的行是有效的python语句;但它不调用函数


然后:您需要在displayEmployee(self)方法中使用self而不是emp1

def displayEmployee(self):
    print('this employee is {} and gets {} dollars'.format(self.name, self.salary))

更好:

def __str__(self):
    return f"this employee is {self.name} and gets {self.salary} dollars"

那你就可以了

print(emp1)

相关问题 更多 >

    热门问题