python面试常问的几个内置装饰器:@staticmethod、@classmethod和@property

之前在python笔试的时候,经常会遇到@staticmethod、@classmethod和@property的用法和区别,这三个也是python的内置装饰器,所以再来总结下:

@staticmethod 类静态方法 与实例方法的区别是没有self参数,并且可以在类不进行实例化的情况下调用
@classmethod 类方法 与实例方法的区别是接收的第一个参数不是self(类实例的指针),而是cls(当前类的具体类型)
@property 属性方法 将一个类方法转变成一个类属性,只读属性

属性@property(获取属性值方法)和@x.setter(设置属性值方法)和@x.deleter(删除属性值方法)表示可读可写可删除

首先我们看一个普通的只读属性函数:

class Student(object):
    def age(self):
        self.__age = 26 #__age为私有属性
        return self.__age

s = Student()
print(s.age)

我们在类中定义了一个age函数,该函数返回一个定值,26,如果我们想要,获得私有属性__age的值26,我们必须调用age()函数:

如果我们给age函数增加一个@property装饰器,达到直接调用s.age输出我们要的26,因此,我们改下上述demo:

class Student(object):
    @property
    def age(self):
        self.__age = 26 #__age为私有属性
        return self.__age

s = Student()
print(s.age)

我们看下输出:

OK,我们的@property发挥奇效,我们说了,我们没有添加@xxx.setter装饰器,因此,age是一个只读属性,如果我们试图修改age的值,我们看下效果,是不是可行?

如果想要age既可读又可写,我们可以这样做:

class Student(object):
    @property
    def age(self):
        return self.__age
    @age.setter
    def age(self,value):
        self.__age = value

s = Student()
s.age=30
print(s.age)

类方法@classmethod

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day
    @classmethod
    def now(cls):
        t = time.localtime()
        return cls(t.tm_year, t.tm_mon, t.tm_mday)
    def __str__(self):
        return '%s-%s-%s' % (self.year, self.month, self.day)
e = Date.now()
print(e)

静态方法@staticmethod

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day
    @staticmethod
    def now():
        t = time.localtime()
        return Date(t.tm_year, t.tm_mon, t.tm_mday)
    def __str__(self):
        return '%s-%s-%s' % (self.year, self.month, self.day)
e = Date.now()
print(e)

转载于:https://blog.csdn.net/xingjingb/article/details/81357793
转载于:https://blog.csdn.net/Appleyk/article/details/77850120?

原文地址:https://www.cnblogs.com/hghua/p/13150101.html