类static staticmethod和模块函数之间的区别

时间:2016-03-05 10:35:59

标签: python function class methods python-module

我正在为我的django应用程序编写一个自定义电子邮件助手以方便个人使用。但我意识到有两种方法可以做同样的事情。

通过导入类并调用其@staticmethod

# email_helper.py
from django.core.mail import send_mail
class EmailHelper(object):
    @staticmethod
    def send(subject, recipients, static_message, html_message):
        send_mail(
            subject = subject,
            from_email = "Bob <bob@example.com>",
            recipient_list = recipients,
            message = static_message,
            html_message = html_message,
            fail_silently = False,
        )

# usage:
from email_helper import EmailHelper
EmailHelper.send(subject="", recipients=[], static_message="", html_message="")
# end_of_usage

导入模块并调用其中的函数

# email_helper.py
from django.core.mail import send_mail
def send(subject, recipients, static_message, html_message):
    send_mail(
        subject = subject,
        from_email = "Bob <bob@example.com>",
        recipient_list = recipients,
        message = static_message,
        html_message = html_message,
        fail_silently = False,
    )

# usage:
import email_helper
email_helper.send(subject="", recipients=[], static_message="", html_message="")
# end_of_usage

这两种方法之间的运行时/编译时/操作/差异是什么?

P.S。我实际上尝试了这两种方法,它们都适用于我的用例。但是,目前我没有太多的生产级工作量来客观地衡量真正的性能优势。我好奇的想法是试图理解python上这两种方法背后的解剖学和科学; - )

P.S。还有另一个StackOverflow问题与这个问题试图提出的问题有些接近。 Module function vs staticmethod vs no decorator。但是,我发现其他问题有点过于宽泛,而这个问题相对更具体。

0 个答案:

没有答案