简体   繁体   English

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

[英]instantiating optional arguments in python class?

So in the event that you have several optional arguments in a class, how would you loop over the optional arguments to set their values after the base instantiation is done? 因此,如果在一个类中有几个可选参数,那么如何在基本实例化完成后遍历可选参数以设置其值? Also looking for any recommendations of more pythonic ways to handle this code overall. 也正在寻找更多建议使用Python方式来整体处理此代码。 Thanks! 谢谢!

required 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',

... etc. ...等

optional 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: 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 = ''

main function to instantiate mysmtp 实例化mysmtp的主要功能

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

optional arguments 可选参数

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

trying to simplifiy setting all of these params if they are present without having a million if's: 尝试简化所有这些参数(如果存在)的设置,而没有一百万个if:

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


main()

how would i expand the value of arg in the for loop and place it in q.{} ? 我将如何在for循环中扩展arg的值并将其放在q.{}

when q.send_message runs it appears that all of the optional variables are not getting set by the loop in main() , so their value is blank as they are default set in __init__ : q.send_message运行时,似乎所有可选变量都没有在main()被循环设置,因此它们的值为空,因为它们是在__init__中默认设置的:

   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 = ''

full source code below. 完整的源代码如下。

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

This is what you might be looking for. 就是您想要的。 You can use *args when you're not sure in the problem how many arguments might pass to your function. 当您不确定问题中有多少个参数可以传递给函数时,可以使用*args It allows you pass an arbitrary number of arguments to your function 它允许您将任意数量的参数传递给函数

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

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