美文网首页
@staticmethod 和 @classmethod

@staticmethod 和 @classmethod

作者: xiaoyaook | 来源:发表于2017-10-05 15:31 被阅读0次

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

相关文章

网友评论

      本文标题:@staticmethod 和 @classmethod

      本文链接:https://www.haomeiwen.com/subject/lzzhyxtx.html