@staticmethod 和 @classmethod

classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all.

class Date(object):

    def __init__(self, day=0, month=0, year=0):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date1 = cls(day, month, year)
        return date1

date2 = Date.from_string('11-09-2012')

classmethod的第一个参数就是类本身,
cls is an object that holds class itself, not an instance of the class.
不管这个方式是从实例调用还是从类调用,它都用第一个参数把类传递过来.

staticmethod可以没有任何参数

@staticmethod
    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999

    # usage:

is_date = Date.is_date_valid('11-09-2012')

就像调用一个普通函数一样,只不过这个函数在Date类里.

上面两个例子都没有创建实例就使用类里面的方法,这应该就是使用这两个装饰器的优势吧.

参考: stackoverflow

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容