python中常用的裝飾器有以下幾種
1.@property
@property是python的一種裝飾器,常用于用來修飾方法。
class DataSet(object):
@property
def method_with_property(self):
return 15
def method_without_property(self):
return 15
l = DataSet()
print(l.method_with_property)
print(l.method_without_property())
2.@abstractmethod
@abstractmethod裝飾器是一種抽象方法,表示基類。
from abc import ABC, abstractmethod
class Foo(ABC):
@abstractmethod
def fun(self):
'''please Implemente in subclass'''
class SubFoo(Foo):
def fun(self):
print('fun in SubFoo')
a = SubFoo()
a.fun()
3.@staticmethoed
@staticmethoed裝飾器不需要表示自身對象的self和自身類的cls參數。
class A(object):
bar = 1
def foo(self):
print 'foo'
@staticmethod
def static_foo():
print 'static_foo'
print A.bar
@classmethod
def class_foo(cls):
print 'class_foo'
print cls.bar
cls().foo()
A.static_foo()
A.class_foo()