Python腳本

python classmethod 與staticmethod區(qū)別

某個函數(shù)前面加上了staticmethod或者classmethod的話,那么這個函數(shù)就可以不通過實例化直接調(diào)用。

@staticmethod不需要表示自身對象的self和自身類的cls參數(shù),就跟使用函數(shù)一樣。
@classmethod也不需要self參數(shù),但第一個參數(shù)需要是表示自身類的cls參數(shù)。
如果在@staticmethod中要調(diào)用到這個類的一些屬性方法,只能直接類名.屬性名或類名.方法名。
而@classmethod因為持有cls參數(shù),可以來調(diào)用類的屬性,類的方法,實例化對象等,避免硬編碼。

(1)staticmethod方法:excel表格轉(zhuǎn)換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()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容