Python OOP from a Java programmer's perspective -
i have oop programming experience in java , have started working on project in python , i'm starting realize python makes me skeptical few things intuitive me. have few questions oop in python.
scenario: i'm writing program send emails. email, to, from, text , subject fields required , other fields cc , bcc optional. also, there bunch of classes implement core mail functionality, derive base class (mailer).
following incomplete code snippet:
class mailer(object): __metaclass__ == abc.abcmeta def __init__(self,key): self.key = key @abc.abstractmethod def send_email(self, mailreq): pass class mailgunmailer(mailer): def __init__(self,key): super(mailgunmailer, self).__init__(key) def send_email(self, mailreq): = mailreq.from = mailreq.to subject= mailreq.subject text = mailreq.text options = getattr(mailreq,'options',none) if(options != none): if mailrequestoptions.bcc in options: #use property pass if mailrequestoptions.cc in options: #use property pass class mailrequest(): def __init__(self,from,to,subject,text): self.from = self.to = self.subject = subject self.text = text def set_options(self,options): self.options = options class mailrequestoptions(): bcc = "bcc" cc = "cc" questions:
the
send_mailmethod can take multiple parameters (from, to, subject, text, cc, bcc, etc.) , 4 of them required in app. since number of parameters method high, decided create wrapper object calledmailrequest, have 4 necessary parameters properties, , other parameters may defined inoptionsdictionary. problem is, here, looking @ code there's no wayoptionsis.dictorlist? also, looking @send_emailmethod, there's no way tellmailreqis. is bad programming practice? should doing else? coming java world, makes me uncomfortable write code can't tell parameters looking @ code. got know annotations in python, don't want use them since they're supported in later versions.since
optionsdict should used specify many other properties (cc,bcc2 of them), i've created new class calledmailrequestoptionsof options may specified inside options dictmailrequestoptionss static strings. is bad practice well, or there better way this? not python specific, know.
in python there no need create object. can use dictionary if want wrap mail request:
mailreq = {'from': 'johnsmith@british.com', 'to': '....', ...}you should try use
*args,**kwargsmethod. can make options simpler:def send_mail(from, to, subject, text, **kwargs), other options can retrieved using e.g.kwargs['bcc']. believe more pythonic.
Comments
Post a Comment