简体   繁体   English

Python:将参数传递给 class 中的方法

[英]Python: passing an argument to a method within a class

So for instance I have a class called Employee and I have a class method designed to raise the wage of an an Employee.例如,我有一个名为 Employee 的 class,我有一个 class 方法,旨在提高员工的工资。 I just have issues actually getting my desired raise for the wage passed into the class method as an argument, it's baffling me.我只是有问题实际上得到我想要的工资作为参数传递给 class 方法,这让我感到困惑。

Class module; Class模块;

Class Employee:
    def __init__(self, name, salary, age):

        self.name = name.title()
        self.salary = salary
        self.age = age

    def raise_wage(self, raise):
        self.salary = self.salary + raise

main module;主模块;

def main():
    e1 = Employee("John Smith", 50000, 42)
    Employee.e1.raise_wage(500)

Passing that 500 in as an arguement is the issue, i get missing positional argument errors for the method etc. How do I pass the argument to the class method?将 500 作为参数传递是问题所在,我得到了该方法的位置参数错误等。如何将参数传递给 class 方法?

Hope this makes sense.希望这是有道理的。

  1. You can't use raise .你不能使用raise It is a reserved word.它是一个保留字。

  2. Use class instead of Class to define a class.使用class而不是Class来定义 class。

  3. Write e1.raise_wage() instead of Employee.e1.raise_wage() .e1.raise_wage()而不是Employee.e1.raise_wage()

class Employee:
    def __init__(self, name, salary, age):
        self.name = name.title()
        self.salary = salary
        self.age = age

    def raise_wage(self, amount):
        self.salary = self.salary + amount

e1 = Employee("John Smith", 50000, 42)
e1.raise_wage(500)

print(e1.salary) # output: 50500

raise is a reserved keyword used to raise an exception, change it to other name and it will work just fine. raise是一个保留关键字,用于引发异常,将其更改为其他名称就可以正常工作。 https://www.w3schools.com/python/ref_keyword_raise.asp https://www.w3schools.com/python/ref_keyword_raise.asp

raise is a reserved keyword in python for raising exception. raise 是 python 中用于引发异常的保留关键字。 use another name for that argument then it will work.为该参数使用另一个名称,然后它将起作用。 And you already created object for Employee so no need to call function with class name again.而且您已经为 Employee 创建了 object,因此无需再次使用 class 名称调用 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM