python - 类(class)员工打印方式

标签 python class methods

我正在学习 jupyter notebooks 和 google colab 中的 python 编程类(class)。

我不明白关于这门课的结果。

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()

我不明白为什么在没有括号的情况下运行该方法不会导致任何错误(实际上该方法未运行),而在有括号的情况下(并且没有通过错误传递必要的变量)

其次,如何避免此类错误?即,如果用户没有传递任何内容,则假设值为零

注意: this question解释了 init 方法并被提议作为解决方案。我的问题是相关的,但那里没有答案

最佳答案

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 被隐式传递)时,返回方法对象。但要真正执行函数,您需要调用它,即使用括号。

为了好玩,将返回的方法对象保存为一个变量并调用它,您会发现您在做同样的事情,因为它们引用的是同一个对象。

现在,当您调用 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 - 类(class)员工打印方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56619007/

相关文章:

python - 创建一个唯一的文件系统路径,没有任何实际文件

python - Numpy - 一维和二维数组的不同行为

Java - 尝试从另一个类访问一个类时出错

javascript - 在javascript中的类定义中添加原型(prototype)

javascript - 是否有 Javascript 信息的中央存储库?

c# - C#中获取用户输入的方法

python - pandas concat 生成 nan 值

python - 如何将值更改为零但不在循环的第一次迭代中

php - 如何在类中实现回调方法 (PHP)

c# - Xamarin WCF BasicHttpBinding-未实现方法或操作