Reputation: 615
The purpose of this script is to send an email to a receivers list, and the code works just for the first receiver but the never works for the rest of the list.
here is the code:
class email:
def __init__(self, sender, subject, message):
self.sender = sender
self.subject = subject
self.message = message
def receivers(self):
receivers = ('adam', 'tom', 'mel')
for receiver in receivers:
return receiver
def send(self):
print('we send email from'.capitalize(), self.sender, 'to', email.receivers().title(), 'and the subject is',
self.subject, 'finally the massage is', self.message)
email = email('sayed', 'morning message', 'wake up man')
email.send()
here is the result:
We send email from sayed to Adam and the subject is morning message finally the massage is wake up man
Upvotes: 0
Views: 235
Reputation: 37960
Whenever a return
statement is executed, the current function is immediately exited. Use either return receivers
(without the loop) to return the entire set instead of just one item, or use yield receiver
to create a generator (if you choose the latter, please read the linked answer to understand what generators are).
Stylistic advice: reusing a function name as a variable name inside that function is likely going to confuse people who read your code.
Upvotes: 4
Reputation: 3749
If tuple of receivers is static, then move this tuple to be class attribute:
class Email: # convenient
_receivers = ('adam', 'tom', 'mel') # _ - to be protected
Upvotes: 0
Reputation: 428
Return
exits the function once it returns a value. It's like a break
.
You get that result, because once you return the first value ('adam'), you exit the function via return
. You should just return
the whole tuple: return receivers
, then in send(self)
:
receivers = email.receivers()
for receiver in receivers:
print('we send email from'.capitalize(), self.sender, 'to', receiver.title(), 'and the subject is',
self.subject, 'finally the massage is', self.message)
Upvotes: 1
Reputation: 1273
your receivers function stops after returning the first receiver, I suggest returning the set and iterate over it
def receivers(self):
return ('adam', 'tom', 'mel')
for receiver in email.receivers():
print('we send email from'.capitalize(), self.sender, 'to', receiver.title(), 'and the subject is',
self.subject, 'finally the massage is', self.message)
Upvotes: 0