python classmethod 与staticmethod区别
某个函数前面加上了staticmethod或者classmethod的话,那么这个函数就可以不通过实例化直接调用。
@staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。
如果在@staticmethod中要调用到这个类的一些属性方法,只能直接类名.属性名或类名.方法名。
而@classmethod因为持有cls参数,可以来调用类的属性,类的方法,实例化对象等,避免硬编码。
(1)staticmethod方法:excel表格转换txt
# -*- coding:utf8 -*-
import os
import sys
from openpyxl import load_workbook
class Cloud(object):
def __init__(self,excel_name):
try:
#python2使用
reload(sys)
# 设置默认编码方式为:UTF8,其他编码方式会报错
sys.setdefaultencoding('utf-8')
except NameError:
pass
self.excel_name = excel_name
# 打开excel(工作薄)
self.workbook = load_workbook(self.excel_name)
def sheet(self):
sheet = self.workbook['最新题目']
return sheet
@classmethod
def create_file(cls,value):
with open('ACP.txt', 'a+', encoding='utf8') as f:
f.write(value)
f.write('\n')
def run(self):
sheet = self.sheet()
if os.path.isfile('ACP.txt'):
os.remove('ACP.txt')
self.create_file('阿里云计算题库\n')
else:
self.create_file('阿里云计算题库\n')
for row in range(2,sheet.max_row+1):
topic_type = sheet.cell(row,2).value.strip()
topic_name = '{} {}'.format(row-1,sheet.cell(row,3).value.strip())
topic_answer = '{} {}'.format('答案',sheet.cell(row,4).value.strip())
topic_analysis = '{} {}'.format('题目解析',sheet.cell(row,6).value)
option_a = "{} {}".format('A',sheet.cell(row,8).value)
option_b = "{} {}".format('B',sheet.cell(row,9).value)
option_c = "{} {}".format('C',sheet.cell(row,10).value)
option_d = "{} {}".format('D',sheet.cell(row,11).value)
option_e = "{} {}".format('E',sheet.cell(row,12).value)
option_f = "{} {}".format('F',sheet.cell(row,13).value)
option_g = "{} {}".format('G',sheet.cell(row,14).value)
self.create_file(topic_name)
self.create_file(topic_type)
if sheet.cell(row,8).value:
self.create_file(option_a)
if sheet.cell(row,9).value:
self.create_file(option_b)
if sheet.cell(row,10).value:
self.create_file(option_c)
if sheet.cell(row,11).value:
self.create_file(option_d)
if sheet.cell(row,12).value:
self.create_file(option_e)
if sheet.cell(row,13).value:
self.create_file(option_f)
if sheet.cell(row,14).value:
self.create_file(option_g)
self.create_file(topic_answer)
self.create_file(topic_analysis)
self.create_file('\r')
if __name__ == '__main__':
cloud = Cloud('阿里云计算题库.xlsx')
cloud.run()
(2)classmethod方法:类方法使用演示
# -*- coding:utf8 -*-
import yaml
class Summary(object):
def __init__(self,select_role):
self.select_role = select_role
@classmethod
def yaml_parse(cls):
with open('total_attribute.yaml') as f:
data = f.read()
return yaml.safe_load(data)
def role_parse(self):
manufacturer_list = list()
total_role_list = list()
info_list = list()
for role in self.yaml_parse():
if role.get('candidates'):
for manufacturer in role.get('candidates'):
if manufacturer.get('manufacturer') not in manufacturer_list:
manufacturer_list.append(manufacturer.get('manufacturer'))
data = {role.get('type'): role.get('candidates')}
if data.keys()[0] == self.select_role:
total_role_list.extend(data.get(self.select_role))
for i in total_role_list:
if i.get('modellist') and isinstance(i.get('modellist'),list):
for model in i.get('modellist'):
model.update({'manufacturer': i.get('manufacturer')})
info_list.append(model)
for manufacturer in manufacturer_list:
manufacturer_list_info = list()
for i in info_list:
if i.get('manufacturer') == manufacturer and i.get('modelname') not in manufacturer_list_info:
manufacturer_list_info.append(i.get('modelname'))
if manufacturer_list_info:
print({manufacturer: manufacturer_list_info})
if __name__ == '__main__':
summary = Summary('HSW.10GE')
summary.role_parse()