在python类中实例化可选参数?

时间:2016-07-20 02:33:34

标签: python class oop

因此,如果在类中有几个可选参数,那么在基本实例化完成后,如何循环使用可选参数来设置它们的值?还寻找更多pythonic方法的任何建议,以整体处理此代码。谢谢!

必需的args:

p = argparse.ArgumentParser()
p.add_argument('-s',
               '--server',
               type=str,
               help='smtp server',
               required='True')
p.add_argument('-p',
               '--port',
               type=int,
               help='smtp server port',

......等等。

可选的args:

p.add_argument('-P',
              '--replyto',
              type=str,
              help='reply to header. rtfrfc')
p.add_argument('-R',
              '--returnpath',
              type=str,
              help='reply to header. rtfrfc')
args = p.parse_args()

init of mysmtp:

class mysmtp:
   def __init__(self, server, port, rcptto, mailfrom, subject,
                displayname='', displayemail='', xsender='',
                replyto='', returnpath=''):
       self.server = server
       self.port = port
       self.rcptto = rcptto
       self.mailfrom = mailfrom
       self.subject = subject
       self.displayname = ''
       self.displayemail = ''
       self.replyto = ''
       self.xsender = ''
       self.filename = ''
       self.returnpath = ''

实例化mysmtp的主要功能

def main():
   q = mysmtp(args.server,
              args.port,
              args.rcptto,
              args.mailfrom,
              args.subject)

可选参数

   optargs = [args.displayname,
           args.displayemail,
           args.xsender,
           args.replyto,
           args.returnpath]

试图简化设置所有这些参数如果它们存在而没有一百万个if:

   for arg in optargs:
      print arg
      if arg:
         q.arg
      print q
   q.send_message()


main()

如何在for循环中展开arg的值并将其放在q.{}

q.send_message运行时,似乎所有可选变量都未被main()中的循环设置,因此它们的值为空,因为它们是__init__中的默认设置:< / p>

   def send_message(self):

       msg = MIMEMultipart('alternative')
       msg['From'] = self.mailfrom
       msg['To'] = self.rcptto
       msg['Subject'] = self.subject

       if self.displayname:
         d = "{} \"<{}>\"\r\n".format(self.displayname, self.displayemail)
       else:
         d = ''
       if self.xsender:
         x = "X-Sender: {} \"<{}>\"\r\n".format(self.displayname, self.displayemail)
       else:
         x = ''
       if self.replyto:
         rto = "Reply-To: {} \"{}\"\r\n".format(self.displayname, self.replyto)
       else:
         rto = ''
       if self.returnpath:
         rpat = "Return-Path: {} \"{}\"\r\n".format(self.displayname, self.returnpath)
       else:
         rpat = ''

下面的完整源代码。

import smtplib
import socket
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import argparse

p = argparse.ArgumentParser()
p.add_argument('-s',
               '--server',
               type=str,
               help='smtp server',
               required='True')
p.add_argument('-p',
               '--port',
               type=int,
               help='smtp server port',
               required='True')
p.add_argument('-r',
               '--rcptto',
               type=str,
               help='to address',
               required='True')
p.add_argument('-m',
              '--mailfrom',
              type=str,
              help='MAIL FROM email headers. ' +
              'please note this email may need to be set ' +
              'as a valid domain you are sending from to ' +
              'bypass spf checks',
              required='True')
p.add_argument('-d',
              '--displayname',
              type=str,
              help='display name to fool mail clients. ' +
              'useful if you cant spoof your MAILFROM',
              required='True')
p.add_argument('-l',
              '--displayemail',
              type=str,
              help='display from email to fool mail clients. ' +
              'useful if you cant spoof your MAILFROM'
              )
p.add_argument('-x',
              '--xsender',
              type=str,
              help='rtfm or rtfrfc' +
              'useful if you cant spoof your MAILFROM',
              )
p.add_argument('-j',
              '--subject',
              type=str,
              help='email subject',
              required='True')
p.add_argument('-f',
              '--filename',
              type=str,
              help='file attachment')
p.add_argument('-P',
              '--replyto',
              type=str,
              help='reply to header. rtfrfc')
p.add_argument('-R',
              '--returnpath',
              type=str,
              help='reply to header. rtfrfc')
args = p.parse_args()

class mysmtp:
   def __init__(self, server, port, rcptto, mailfrom, subject,
                displayname='', displayemail='', xsender='',
                replyto='', returnpath=''):
       self.server = server
       self.port = port
       self.rcptto = rcptto
       self.mailfrom = mailfrom
       self.subject = subject
       self.displayname = ''
       self.displayemail = ''
       self.replyto = ''
       self.xsender = ''
       self.filename = ''
       self.returnpath = ''

   def send_message(self):

       msg = MIMEMultipart('alternative')
       msg['From'] = self.mailfrom
       msg['To'] = self.rcptto
       msg['Subject'] = self.subject

       if self.displayname:
         d = "{} \"<{}>\"\r\n".format(self.displayname, self.displayemail)
       else:
         d = ''
       if self.xsender:
         x = "X-Sender: {} \"<{}>\"\r\n".format(self.displayname, self.displayemail)
       else:
         x = ''
       if self.replyto:
         rto = "Reply-To: {} \"{}\"\r\n".format(self.displayname, self.replyto)
       else:
         rto = ''
       if self.returnpath:
         rpat = "Return-Path: {} \"{}\"\r\n".format(self.displayname, self.returnpath)
       else:
         rpat = ''
       print rto
       body = "{}{}{}{}sent w/ smtplib and email.mime py libs".format(d,x,rto,rpat)
       print body
       content = MIMEText(body, 'plain')
       msg.attach(content)
       if self.filename:
           f = file(self.filename)
           attachment = MIMEText(f.read())
           attachment.add_header('Content-Disposition',
                                 'attachment',
                                 filename=self.filename)
           msg.attach(attachment)
           print f
       try:
           print '[+] attempting to send message'
           s = smtplib.SMTP(self.server, self.port)
           s.sendmail(self.mailfrom, self.rcptto, msg.as_string())
           print '[$] successfully sent through {}:{}'.format(self.server,
                                                              self.port)
       except socket.error as e:
           print '[!] could not connect'


#   def __init__(self, server, port, rcptto, mailfrom, subject,
 #                  displayname='', displayemail='', xsender='',
 #                                  replyto='', returnpath=''):


def main():
   q = mysmtp(args.server,
              args.port,
              args.rcptto,
              args.mailfrom,
              args.subject)

   optargs = [args.displayname,
           args.displayemail,
           args.xsender,
           args.replyto,
           args.returnpath]

   for arg in optargs:
      print arg
      if arg:
         q.arg = arg
      print q
   q.send_message()


main()

1 个答案:

答案 0 :(得分:1)

你可能正在寻找

This。如果您不确定问题可能传递给您的函数有多少参数,则可以使用*args。它允许您向函数传递任意数量的参数