[英]Python can you ignore time.sleep outside of function but not inside?
[英]Python: How can you ignore an argument in a function?
我想知道是否有一種方法來定義帶有參數的函數,但是如果它們不適用,則忽略函數中的某些參數。
例如,在這段代碼中,我試圖從參考表中查找唯一的傘下的聯系人以向其發送電子郵件,但是該表可能包含行,其中的聯系人可能僅限於一兩個人或五個人。 如果是這樣,則應忽略第一個/第二個聯系人之后的所有其他聯系人的參數。
reference = [
{'Code': '10', "Group": "There", "Contact": "Me@there.com",
"Contact2": him@there.com", Contact3": "you@there.com"},
{'Code': '11', "Group": "Here", "Contact": "she@here.com", "Contact2": "her@here.com"},
{'Code': '20', "Group": "Everywhere", "Contact": "them@everywhere.com"}
]
import win32com.client
def send_email(contact, contact2, contact3, contact4, contact5):
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "Email for %s" %group
newMail.Body = "Message"
newMail.To = contact
newMail.CC = contact2, contact3, contact 4, contact5
#newMail.BCC = "address"
attachment1 = file
newMail.Attachments.Add(attachment1)
#newMail.display()
newMail.Send()
count = 0
for Contact in reference:
send_email(reference['Contact'][count])
count = count + 1
您可以使用可變數量的參數,但是它們必須是函數的最后一個參數。
def send_email(file, group, *contacts):
# ...
newMail.CC = ', '.join(contacts)
*
符號會根據結尾的參數創建一個元組,無論您提供了多少。
但是,在您的情況下,輸入數據的結構只是對您的應用程序來說很尷尬。 您應該使它看起來像這樣:
reference = [
{'Code': '10', "Group": "There", "Contacts": ["Me@there.com", "him@there.com", "you@there.com"]},
{'Code': '11', "Group": "Here", "Contacts": ["she@here.com", "her@here.com"]},
{'Code': '20', "Group": "Everywhere", "Contacts": ["them@everywhere.com"]}
]
def send_email(contacts):
# ...
newMail.To = contacts[0]
newMail.CC = ', '.join(contacts[1:])
您可以使用類似:
def myFunction(*arg):
這使您可以使用可變數量的參數。
我絕對是在想這個。 我最終要做的是:
import win32com.client
table = [
{'Code': '10', "Group": "Turn", "Contact": "A@there.com; B@there.com"},
{'Code': '20', "Group": "A9", "Contact": "Z@here.com; Y@here.com; H@here.com"},
{'Code': '30', "Group": "AppNexus", "Contact": "N@OverThere.com"}
]
def send_email(group, file, contact):
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "Email for %s" %group
newMail.Body = "Message"
newMail.To = contact
#newMail.CC =
#newMail.BCC = "address"
attachment1 = file
newMail.Attachments.Add(attachment1)
#newMail.display()
newMail.Send()
count = 0
for Contact in table:
info = get_info(table['Code'][count])
file = make_file(table['Code'][count], info)
send_email(file, table['Code'][count], table['Group'], table['Contact'][count])
count = count + 1
字典值僅需使用分號,並使用引號將所有電子郵件的總和包裹起來。
電話,
newMail.To =
只需使用一個字符串值,Outlook在實際的Outlook應用程序中將分號作為分隔符。 因此,您只需傳遞並打開引號,列出所有電子郵件,並關閉該特定組的聯系人條目中最后一封電子郵件的引號,就可以傳遞包含多封電子郵件的條目,而不必將它們放入詞典中的單獨列表中。 該表中的大多數電子郵件都不會更改,因此也無需擔心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.