跳到主要內容

發表文章

目前顯示的是 12月, 2018的文章


Python-程式優化設計-module

class Objects, values and types CPython implementation detail:  For CPython,  The standard type hierarchy User-defined functions __doc__ The function’s documentation string, or  None  if unavailable; not inherited by subclasses Writable __name__ The function’s name Writable __qualname__ The function’s  qualified name New in version 3.3. Writable __module__ The name of the module the function was defined in, or  None  if unavailable. Writable __defaults__ A tuple containing default argument values for those arguments that have defaults, or  None  if no arguments have a default value Writable __code__ The code object representing the compiled function body. Writable __globals__ A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined. Read-only __dict__ The namespace supporting arbitrary function attributes. Writable __closure__ None  or a tuple of cells that contain bindings for

Python-開啟檔案-word

Python 開啟檔案 word import docx doc = docx.Document() doc.add_heading('Hello world!, level 1', level=1) doc.add_paragraph('Hello world!') doc.save('demo.docx') doc2 = docx.Document('demo.docx') text = [] for para in doc.paragraphs: text.append(para.text) print(text) 程式碼說明 匯入必要模組 定義檔案物件 增加標題 增加段落 儲存 定義檔案物件,從檔案中讀取,並印出

Python-開啟檔案-excel

Python 開啟檔案 excel 安裝: linux、mac :pip3 install openpyxl、pip3 install xlwt、pip3 install xlrd windows    :之後補上 程式碼說明 2007年版後 寫入 from openpyxl import Workbook,load_workbook wb = Workbook() ws = wb.active ws1 = wb.create_sheet('Mysheet') ws2 = wb.create_sheet('Mysheet', 0) ws1.title = 'New Title' print(wb.sheetnames) ws['A4'] = 4 ws.cell(row=4, column=2, value=10) wb.save('demo.xlsx')  讀取 wb_load = load_workbook('demo.xlsx')  sheet_ranges = wb_load['Sheet'] print(sheet_ranges['A4'].value) 2007年版前 寫入 import xlwt from datetime import datetime style0 = xlwt.easyxf('font: name Times New Roman, \ color-index red, bold on',num_format_str='#,##0.00') style1 = xlwt.easyxf(num_format_str='D-MMM-YY') wb = xlwt.Workbook() ws = wb.add_sheet('A Test Sheet') ws.write(0, 0, 124, style0) ws.write(1, 0, datetime.now(), sty

Python-資料庫-mongodb-pymongo

Python 資料庫 mongodb-pymongo 安裝: linux、mac:pip3 install pymongo windows: import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") db = client['demo_db'] col = db['demo_col'] dict1 = { "name": "ab123ab456g", "day": "1890-04-05" } result = col.insert_one(dict1)  dict2 = [   { "name": "ki", "day": "1666-1-1"},   { "name": "aa", "day": "1222-11-11"},   { "name": "gg-gg", "day": "1333-02-22"},   { "name": "T-T", "day": "1444-03-02"},   { "name": "f-f", "day": "1555-01-01"} ] result = col.insert_many(dict2) result = col.find_one() print(result) results = col.find() for result in col.find(): print(result) results = col.find() query = {'

Python-資料庫-mysql-sqlalchemy

Python 資料庫 mysql-sqlalchemy 安裝 Linux、mac : pip3 install SQLAlchemy windows     :之後補充 第一部分 from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory', echo=False) Base = declarative_base() Session = sessionmaker(bind=engine) 第二部分 from test_sqlalchemy import * from sqlalchemy import Column, Integer, String class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr(self): return "<User(name={})>".format(self.name) 第三部分 from test_sqlalchemy import * from build_model import * Base.metadata.create_all(engine) user1 = User(name='user1', fullname='user1', password='user1') user2 = User(name='user2', fullname='user2

Python-資料庫-mysql-pymysql

Python 資料庫 mysql-pymysql 安裝: linux、mac:pip3 install PyMySql windows    : 之後補充 import pymysql.cursors connection = pymysql.connect(host='ip', user='root', password='password', db='database_name',charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) #    CREATE TABLE `users` ( #    `id` int(11) NOT NULL AUTO_INCREMENT, #    `email` varchar(255) COLLATE utf8_bin NOT NULL, #    `password` varchar(255) COLLATE utf8_bin NOT NULL, #    PRIMARY KEY (`id`) #) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin #AUTO_INCREMENT=1 ; with connection.cursor() as cursor:     sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"     cursor.execute(sql, ('ab123ab456g@example.com', 'very-secret')) connection.commit() with connection.cursor() as cursor:     sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"     cursor.execute(sql, ('ab123ab456g@example.com',))  

Python-設計模式-拜訪模式

Python 設計模式 拜訪模式 from abc import ABCMeta, abstractmethod NOT_IMPLEMENTED = "You should implement this." class CarElement:     __metaclass__ = ABCMeta     @abstractmethod     def accept(self, visitor):         raise NotImplementedError(NOT_IMPLEMENTED) class Body(CarElement):     def accept(self, visitor):         visitor.visitBody(self) class Engine(CarElement):     def accept(self, visitor):         visitor.visitEngine(self) class Wheel(CarElement):     def __init__(self, name):         self.name = name     def accept(self, visitor):         visitor.visitWheel(self) class Car(CarElement):     def __init__(self):         self.elements = [             Wheel("front left"), Wheel("front right"),             Wheel("back left"), Wheel("back right"),             Body(), Engine()         ]     def accept(self, visitor):         for element in self.elements:             element.accept(visitor)         vis

Python-設計模式-解譯器模式

Python 設計模式 解譯器模式 class Expression: def interpret(self, context): pass class TerminalExpresssion(Expression): def __init__(self): self.data = '' def terminalExpreession(self, data): self.data = data def interpret(self, context): if self.data in context: return True return False class AddExpression(Expression): def __init__(self): self.expr1 = '' self.expr2 = '' def addExpreession(self, expr1, expr2): self.expr1 = expr1 self.expr2 = expr2 def interpret(self, context): return self.expr1.interpret(context) and expr2.interpret(context) class OrExpression(Expression): def orExpreession(self, expr1, expr2): self.expr1 = expr1 self.expr2 = expr2 def interpret(self, context): return self.expr1.interpret(context) or expr2.interpret(context) T1 = TerminalExpresssion() T2 = TerminalExpresssion() T1.terminalExpreession('Name1') T2.terminalExpreession('Human') A1 = OrExpression() A

Python-設計模式-備忘錄模式

Python 設計模式 備忘錄模式 class Memento:     def __init__(self, state):        self.state = state     def GetState(self):        return self.state  class Origniator:     def __init__(self):        self.state = ''     def GetState(self):        return self.state     def SetState(self, state):        self.state = state     def SaveStateToMemeto(self):        return Memento(self.state)     def getStateFromMemeto(self, Memento):        self.state = Memento.GetState()  class CareTaker:     def __init__(self):        self. MementoList = []     def Add(self, memento):        self.MementoList.append(memento)     def GetMementoIndex(self, index):        return self.MementoList[index]  O = Origniator()  C = CareTaker()  O.SetState('1 state 1')  O.SetState('2 state 2')  C.Add(O.SaveStateToMemeto())  O.SetState('3 state 3')  C.Add(O.SaveStateToMemeto())  O.SetState('4 state 4')  print('Current State : ' + O.GetState()) 

Python-設計模式-狀態模式

Python 設計模式 狀態模式 class A:     def __init__(self):        self.State = ''     def SetState(self, state):        self.State = state     def GetState(self):        return self.State  class State:     def ChangeState(self, obj):        pass class StartState(State):     def ChangeState(self, obj):        print('setting Start State')        obj.SetState('Start')  class EndState(State):     def ChangeState(self, obj):        print('setting End State')        obj.SetState('End')  a = A()  S = StartState()  S.ChangeState(a)  print(a.GetState())  E = EndState()  E.ChangeState(a)  print(a.GetState()) 程式碼說明 定義要被改變狀態的類別,定義state介面,定義改變狀態類別。設定物件、改變狀態。

程式設計概念-設計模式-Behavioral-雜談

Behavioral 雜談 模板模式:相同類型物件,有方法上細節的不同時,用覆寫的方式修改方法 責任鍊模式:主要針對權限有關的工作,或是需要層層把關的工作。 命令模式:下達命令後,統一由介面呼叫。 解譯器模式:下達於法,轉變成要的動作 訪問者模式:對於物件整體,進行一次拜訪,拜訪時可以執行特定動作 觀察者模式:當物件狀態改變時,通知相關人員 迭代器模式:將同類型物件存於清單中,此清單可迭代。 中介者模式:將不同物件包到中介者中,透過中介者的方法進行溝通。 備忘錄模式:將物件狀態儲存,需要時可以反闈 狀態模式:抽換狀態 策略模式:抽換方法

python-設計模式-觀察器模式

python 設計模式 觀察器模式 class Subject:     def __init__(self):        self.State = ''        self.OList = []     def GetState(self):        return self.State     def SetState(self, state):        self.State = state        self.NotifyObeservers()     def AddObeserver(self,observer):        self.OList.append(observer)     def RemoveObeserver(self,observer):        self.OList.remove(observer)     def NotifyObeservers(self):        for O in self.OList:           O.Update()  class Observer:     def __init__(self,name,subject):        self.name = name        self.Subject = subject     def Update(self):        print(self.name,self.Subject.GetState())  S1 = Subject()  O1 = Observer('O1',S1)  O2 = Observer('O2',S1)  S1.AddObeserver(O1)  S1.AddObeserver(O2)  S1.SetState('Update')  S1.SetState('Update2') S1.SetState('Update3') 程式碼說明 定義被觀察者,在定義觀察者,建立被觀察者,建立觀察者,把被觀察者方方入觀察者,把觀察者方入被觀察者中的觀察清單,概念狀態,改變時,則會通知狀態更新。

python-設計模式-迭代器模式

python 設計模式 迭代器模式 class Item:    def __init__(self, name, price):       self.name = name        self.price = price     def __str__(self):        return "{}: $ {}".format(self.name, self.price)  class MenuIterator:     def __init__(self, items):        self.indx = 0        self.items = items     def has_next(self):        return False if self.indx >= len(self.items) else True      def next(self):        item = self.items[self.indx] self.indx += 1 return item      def remove(self):        return self.items.pop()  class Menu:      def __init__(self):         self.items = []      def add(self, item):         self.items.append(item)      def iterator(self):         return MenuIterator(self.items)  i1 = Item("spaghetti", 7.50)  i2 = Item("hamburger", 6.00)  i3 = Item("chicken sandwich", 6.50)  menu = Menu()  menu.add(i1)  menu.add(i2)  menu.add(i3)  print("Displaying Menu:")  iterator