在Python中调用内部函数的变量

时间:2013-12-28 03:37:33

标签: python function

我知道我之前已经问过这样的问题,但是我的代码更加清晰,而且我仍然遇到问题。

我的代码是这样的:

    class Email_Stuff:
        def Get_From_Email():
            #code to open up window and get email address
            emailaddr = #the input
            return emailaddr
        def Get_To_Email():
            #code to open up window and get to email address
            recipaddr = #the input
            return recipaddr
        def Get_Email_Address():
            #code to open up window and get email username
            EmailUser = #the input
            return EmailUser
        def Get_Email_Password():
            #code to open up window and get email password
            EmailPass = #the input
            return EmailPass
        def Send_Email():
            import smtplib
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.login((EmailUser),(EmailPass))
            message = "Python Test Email"
            server.sendmail(emailaddr,recipaddr,message)

我需要将变量emailaddrrecipaddrEmailUserEmailPass添加到函数Send_Email中。我不知道我怎么能这样做,因为当我运行这段代码时,它告诉我“全局名称没有被定义”。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

通过添加前缀“self”,使emailaddr,recipaddr,EmailUser和EmailPass成为实例变量。

class Email_Stuff():
    def Get_From_Email(self):
        #code to open up window and get email address
        self.emailaddr = #the input
    def Get_To_Email(self):
        #code to open up window and get to email address
        self.recipaddr = #the input
    def Get_Email_Address(self):
        #code to open up window and get email username
        self.EmailUser = #the input
    def Get_Email_Password(self):
        #code to open up window and get email password
        self.EmailPass = #the input
    def Send_Email(self):
        import smtplib
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.login((self.EmailUser),(self.EmailPass))
        message = "Python Test Email"
        server.sendmail(self.emailaddr,self.recipaddr,self.message)

instance = Email_Stuff()
instance.Get_From_Email()
instance.Get_To_Email()
instance.Get_Email_Address()
instance.Get_Email_Password()
instance.Send_Email()
BTW,方法名称应为小写。

答案 1 :(得分:0)

首先,如果您希望这些函数与与此类的实例关联的方法,那么每个方法都需要引用实例本身作为第一个参数,通常指定为self,尽管您可以命名它你喜欢什么。

例如:

 def Get_Email_Password(self):
    #code to open up window and get email password
    EmailPass = #the input
    return EmailPass

接下来,您有两个选项可以为sendmail准备好值。您可以在Send_Email方法中调用每个方法,并为每个方法存储返回的值。这看起来像这样:

def Send_Email(self):
    emailaddr = self.Get_For_Email()
    recipaddr = self.Get_Email_Address()
    ...

或者您可以将值存储为实例变量,而不是将其返回。所以,你会有这样的事情:

 def Get_Email_Password(self):
    #code to open up window and get email password
    EmailPass = #the input
    self.emailaddr = EmailPass

然后,在您的Send_Email方法中,您将引用已保存的实例变量:

def Send_Email(self):
    ...
    server.sendmail(self.emailaddr, self.recipaddr, self.message)

你如何选择这件事取决于你,但我更喜欢第一种方式。我还建议你阅读PEP8