这是我参与8月更文挑战的第3天,活动详情查看:8月更文挑战
介绍
python 语言中有很多内置的函数,运用起来使代码注了入灵魂,这也称为 "语法糖"。 今天介绍使用内置装饰器 @staticmethod、@classmethod 它们的主要作用是将类方法封装为普通函数, 如下案例分享给大家。
@staticmethod 静态装饰器用法
下列中在 C 类中,封装了handel_array()函数。 使用静态装饰器的含义是将此类方法,转化成了函数。 再次调用handle_array()函数时,无需实例化类,直接调用即可。
普通函数中,无需在传入 self 关键字语法。
class C(object):
def __init__(self, word):
self.word = word
@staticmethod
def handle_array():
print(['a'] * 10)
def get_word(self):
print(self.word)
C.handle_array()
@classmethod 类装饰器用法
此案例中,在 DemoView中封装了两个@classmethod类装饰器, 它的主要作用是将该方法转换成类函数,对比@staticmethod静态装饰器,类装饰器函数它可以调用类中的其他的方法, 也可以继承调用父类中的方法。
下面例子中,Demoview类中demo1_post()类函数,就调用了父类方法_post()。
类装饰器,可以直接调用 DemoView.demo1_post(), 无需实例化。 因为@classmethod类装饰器已经将类方法转换成了函数,则直接调用即可。
class ConnectServer(object):
"""requests 连接池"""
def __init__(self):
self.ip='127.0.0.1'
self.port='80'
def _post(self, *args, **kwargs):
try:
response = requests.post(
'http://' + self.ip + ':' + self.port + kwargs['url'],
data=kwargs['data'],
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
return json.loads(response.text)
except Exception as e:
return {'code': 30000, 'message': '连接 %s 服务器网络不可达' % self.ip, 'except': str(e)}
class DemoView(ConnectServer):
"""Demo1"""
@classmethod
def demo1_post(cls):
# request 数据发送
response = cls()._post(url='/api/demo1', data='data')
return response
@classmethod
def demo2_post(cls):
# request 数据发送
response = cls()._post(url='/api/demo2', data='data')
return response
DemoView.demo1_post()
总结,使用@staticmethod、@classmethod进行封装,使代码进行逻辑处理更加清晰、减少代码冗余性。 更多的Python特性,会陆续更新中。 请大家多多关注~~