Python 类中常用的装饰器

1.

classmethod

可以将类函数不经实例化直接被调用

2.

staticmethod

将函数不经实例化而直接被调用,但被装饰的类函数不能传self cls 参数,也不能调用其他类函数和类变量

3.

property

将类函数执行,免去括号,类似于直接调用属性(变量)

class Test(object):
    def __init__(self, a):
        self.a = a

    def run(self):
        print('run')
        self.dump()
        self.sleep()

    @classmethod
    def dump(cls):
        print('dump')
        #cls.run()

    @staticmethod
    def sleep():
        print('i want sleep')

t = Test('a')
t.run()
# Test.dump()
# print('-----')
# Test.sleep()
# t.sleep()
# t.dump()

class Test1(object):
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        self.__name = value

t1 = Test1(name='dewei')
print(t1.name)
t1.name = '小慕'
print(t1.name)

你可能感兴趣的:(Python,python,开发语言)