python - 如何处理python类中两个参数中的多个值

标签 python

我想创建一个像这样的Python类:

类.py

class MyClass(object):
    def __init__(self, email, delay_time=0):
        print email
        print delay_time
if __name__ == "__main__":
    a = MyClass()

email 参数是强制性的,并且应该能够包含多个值,delay_time 应该是一个可选参数。我想这样调用它:

python class.py abc@email.com abc1@email.com abc2@email.com 3600
python class.py abc@email.com abc1@email.com

我已经用 docopt 尝试过这个,但也没有运气。请提出建议。

最佳答案

尝试这个脚本

import sys
class MyClass(object):
    def __init__(self, emails, delay_time=0):
        for email in emails:
            print email
        print delay_time
if __name__ == "__main__":
    if len(sys.argv)>1:
        emails = sys.argv[1:-1]
        delay = sys.argv[-1]
        try:
            delay = int(delay)
        except ValueError:
            emails.append(delay) #there's no delay
            delay=0
        a = MyClass(emails,delay_time=delay)

这是输出

$:~/dev/stack$ python class.py abc@email.com abc1@email.com abc2@email.com 3600
abc@email.com
abc1@email.com
abc2@email.com
3600
$:~/dev/stack$ python class.py abc@email.com abc1@email.com
abc@email.com
abc1@email.com
0

关于python - 如何处理python类中两个参数中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34607184/

相关文章:

python - Altair 散点图添加了不需要的线条

Python 多处理。如何将 XMLRPC ServerProxy 对象排入队列

python - Pandas 0.21 在 get_dummies() 之后重新索引()

python - 如何用py2exe打包psutil?

python - 在创建时读取文件的 pyinotify 错误?

python - 从两个列表创建自定义字符串

python - 指定层的顺序

python - 包含字典的 pyspark 数据框列的总和

Python:短坐标函数意外更改传入参数值

python - 为redis动态命名元组