标签: positional-argument

如何让 argparse 识别跟随可变长度可选参数的位置参数?

我正在编写一个脚本,该脚本将用于合并多个输入文件,生成一个输出文件,并且我想使用argparse. 对我来说,最自然的方法是使用一个可选输入 ,-i它接受一个或多个输入文件名,后跟一个位置参数,表示输出文件名。这是我的想法的一个例子:

#!/usr/bin/env python3
"""
Script for merging input files
"""
import argparse

script_docstring = 'Read some input files and create a merged output.'
parser = argparse.ArgumentParser(description=script_docstring)
# Optional input file names
parser.add_argument('-i --inputs', nargs='+', type=str, required=True,
                    help='Input file names', dest='inputs')
# Positional output file name
parser.add_argument('fname_out', type=str, help='Output file name')
args = parser.parse_args()

# Display what the user chose at the command line
print(args.inputs)
print(args.fname_out)
Run Code Online (Sandbox Code Playgroud)

当我打印由 创建的自动生成的帮助消息时argparse,调用签名看起来就像我想要的那样:

> ./mergefiles.py --help
usage: mergefiles.py …
Run Code Online (Sandbox Code Playgroud)

python optional-parameters argparse positional-argument

5
推荐指数
1
解决办法
649
查看次数

位置参数

我试图了解如何function解释此参数:

def f(a, *, b):
   return a, b
Run Code Online (Sandbox Code Playgroud)

看来这function会强制调用者f()使用 2 个参数进行调用,并且第二个参数应始终是命名b=参数。我如何从function签名中破译这个?为什么它不允许我为 指定中间参数*

python function positional-argument

2
推荐指数
1
解决办法
4431
查看次数

缺少 1 个必需的位置参数:'y'

我创建了一个Python类:

class calculator:
    
    def addition(self,x,y):
        added = x + y
        print(added)
        
    def subtraction(self,x,y):
        sub = x - y
        print(sub)

    def multiplication(self,x,y):
        mult = x * y
        print(mult)

    def division(self,x,y):
        div = x / y
        print(div)
Run Code Online (Sandbox Code Playgroud)

现在,当我像这样调用该函数时:

calculator.addition(2,3)
Run Code Online (Sandbox Code Playgroud)

我收到错误:

addition() 缺少 1 个必需的位置参数:'y'

问题是什么?我可以这样称呼它的解决方案是什么addition(2,3)

python typeerror python-3.x positional-argument

1
推荐指数
1
解决办法
1万
查看次数

Python 类显示“缺少 1 个必需的位置参数:'self'”

我正在制作一个Python类,其中有员工的姓名、工资和休假数量作为属性,并试图显示员工的最终工资扣除他/她没有来的日子的工资,但它显示一个错误。错误是:

    TypeError: Employee.f_salary() missing 1 required positional argument: 'self'
      
Run Code Online (Sandbox Code Playgroud)

我写了代码:

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

    def f_salary(self):
        self.f_salary1 = self.salary - 500 * int(self.no_of_leaves)

    def display(self):
        print(f"Employee's name: {self.name}\nEmployee's monthly salary: 
        {self.salary}\nNo.of leaves that employee has taken: {self.no_of_leaves}")

nol = input("No. of leaves the employee has taken: ")

john_smith = Employee('John Smith', 182500, nol)

Employee.f_salary()
Employee.display()
Run Code Online (Sandbox Code Playgroud)

python oop class positional-argument

0
推荐指数
1
解决办法
1万
查看次数