一 類中定義的函數分成兩大類
一:綁定方法(綁定給誰,誰來調用就自動將它本身當作第一個參數傳入):
1. 綁定到類的方法:用classmethod裝飾器裝飾的方法。
為類量身定制
類.boud_method(),自動將類當作第一個參數傳入
(其實對象也可調用,但仍將類當作第一個參數傳入)
2. 綁定到對象的方法:沒有被任何裝飾器裝飾的方法。
為對象量身定制
對象.boud_method(),自動將對象當作第一個參數傳入
(屬於類的函數,類可以調用,但是必須按照函數的規則來,沒有自動傳值那么一說)
二:非綁定方法:用staticmethod裝飾器裝飾的方法
1. 不與類或對象綁定,類和對象都可以調用,但是沒有自動傳值那么一說。就是一個普通工具而已
注意:與綁定到對象方法區分開,在類中直接定義的函數,沒有被任何裝飾器裝飾的,都是綁定到對象的方法,可不是普通函數,對象調用該方法會自動傳值,而staticmethod裝飾的方法,不管誰來調用,都沒有自動傳值一說
二 綁定方法
綁定給對象的方法(略)
綁定給類的方法(classmethod)
classmehtod是給類用的,即綁定到類,類在使用時會將類本身當做參數傳給類方法的第一個參數(即便是對象來調用也會將類當作第一個參數傳入),python為我們內置了函數classmethod來把類中的函數定義成類方法

HOST='127.0.0.1' PORT=3306 DB_PATH=r'C:\Users\Administrator\PycharmProjects\test\面向對象編程\test1\db'
import settings class MySQL: def __init__(self,host,port): self.host=host self.port=port @classmethod def from_conf(cls): print(cls) return cls(settings.HOST,settings.PORT) print(MySQL.from_conf) #<bound method MySQL.from_conf of <class '__main__.MySQL'>> conn=MySQL.from_conf() conn.from_conf() #對象也可以調用,但是默認傳的第一個參數仍然是類
三 非綁定方法
在類內部用staticmethod裝飾的函數即非綁定方法,就是普通函數
statimethod不與類或對象綁定,誰都可以調用,沒有自動傳值效果
import hashlib import time class MySQL: def __init__(self,host,port): self.id=self.create_id() self.host=host self.port=port @staticmethod def create_id(): #就是一個普通工具 m=hashlib.md5(str(time.time()).encode('utf-8')) return m.hexdigest() print(MySQL.create_id) #<function MySQL.create_id at 0x0000000001E6B9D8> #查看結果為普通函數 conn=MySQL('127.0.0.1',3306) print(conn.create_id) #<function MySQL.create_id at 0x00000000026FB9D8> #查看結果為普通函數
四 classmethod與staticmethod的區別

import settings class MySQL: def __init__(self,host,port): self.host=host self.port=port @staticmethod def from_conf(): return MySQL(settings.HOST,settings.PORT) # @classmethod #哪個類來調用,就將哪個類當做第一個參數傳入 # def from_conf(cls): # return cls(settings.HOST,settings.PORT) def __str__(self): return '就不告訴你' class Mariadb(MySQL): def __str__(self): return '<%s:%s>' %(self.host,self.port) m=Mariadb.from_conf() print(m) #我們的意圖是想觸發Mariadb.__str__,但是結果觸發了MySQL.__str__的執行,打印就不告訴你:
五 練習
定義MySQL類
1.對象有id、host、port三個屬性
2.定義工具create_id,在實例化時為每個對象隨機生成id,保證id唯一
3.提供兩種實例化方式,方式一:用戶傳入host和port 方式二:從配置文件中讀取host和port進行實例化
4.為對象定制方法,save和get_obj_by_id,save能自動將對象序列化到文件中,文件路徑為配置文件中DB_PATH,文件名為id號,保存之前驗證對象是否已經存在,若存在則拋出異常,;get_obj_by_id方法用來從文件中反序列化出對象

原文鏈接:http://www.cnblogs.com/dkblog/archive/2011/10/10/2205200.html Python官方Doc:《20.15. uuid — UUID objects according to RFC 4122》 UUID的算法介紹:《A Universally Unique IDentifier (UUID) URN Namespace》 概述: UUID是128位的全局唯一標識符,通常由32字節的字符串表示。 它可以保證時間和空間的唯一性,也稱為GUID,全稱為: UUID —— Universally Unique IDentifier Python 中叫 UUID GUID —— Globally Unique IDentifier C# 中叫 GUID 它通過MAC地址、時間戳、命名空間、隨機數、偽隨機數來保證生成ID的唯一性。 UUID主要有五個算法,也就是五種方法來實現: 1、uuid1()——基於時間戳 由MAC地址、當前時間戳、隨機數生成。可以保證全球范圍內的唯一性, 但MAC的使用同時帶來安全性問題,局域網中可以使用IP來代替MAC。 2、uuid2()——基於分布式計算環境DCE(Python中沒有這個函數) 算法與uuid1相同,不同的是把時間戳的前4位置換為POSIX的UID。 實際中很少用到該方法。 3、uuid3()——基於名字的MD5散列值 通過計算名字和命名空間的MD5散列值得到,保證了同一命名空間中不同名字的唯一性, 和不同命名空間的唯一性,但同一命名空間的同一名字生成相同的uuid。 4、uuid4()——基於隨機數 由偽隨機數得到,有一定的重復概率,該概率可以計算出來。 5、uuid5()——基於名字的SHA-1散列值 算法與uuid3相同,不同的是使用 Secure Hash Algorithm 1 算法 使用方面: 首先,Python中沒有基於DCE的,所以uuid2可以忽略; 其次,uuid4存在概率性重復,由無映射性,最好不用; 再次,若在Global的分布式計算環境下,最好用uuid1; 最后,若有名字的唯一性要求,最好用uuid3或uuid5。 編碼方法: # -*- coding: utf-8 -*- import uuid name = "test_name" namespace = "test_namespace" print uuid.uuid1() # 帶參的方法參見Python Doc print uuid.uuid3(namespace, name) print uuid.uuid4() print uuid.uuid5(namespace, name)

#settings.py內容 ''' HOST='127.0.0.1' PORT=3306 DB_PATH=r'E:\CMS\aaa\db' ''' import settings import uuid import pickle import os class MySQL: def __init__(self,host,port): self.id=self.create_id() self.host=host self.port=port def save(self): if not self.is_exists: raise PermissionError('對象已存在') file_path=r'%s%s%s' %(settings.DB_PATH,os.sep,self.id) pickle.dump(self,open(file_path,'wb')) @property def is_exists(self): tag=True files=os.listdir(settings.DB_PATH) for file in files: file_abspath=r'%s%s%s' %(settings.DB_PATH,os.sep,file) obj=pickle.load(open(file_abspath,'rb')) if self.host == obj.host and self.port == obj.port: tag=False break return tag @staticmethod def get_obj_by_id(id): file_abspath = r'%s%s%s' % (settings.DB_PATH, os.sep, id) return pickle.load(open(file_abspath,'rb')) @staticmethod def create_id(): return str(uuid.uuid1()) @classmethod def from_conf(cls): print(cls) return cls(settings.HOST,settings.PORT) # print(MySQL.from_conf) #<bound method MySQL.from_conf of <class '__main__.MySQL'>> conn=MySQL.from_conf() conn.save() conn1=MySQL('127.0.0.1',3306) conn1.save() #拋出異常PermissionError: 對象已存在 obj=MySQL.get_obj_by_id('7e6c5ec0-7e9f-11e7-9acc-408d5c2f84ca') print(obj.host)
其他練習

class Date: def __init__(self,year,month,day): self.year=year self.month=month self.day=day @staticmethod def now(): #用Date.now()的形式去產生實例,該實例用的是當前時間 t=time.localtime() #獲取結構化的時間格式 return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建實例並且返回 @staticmethod def tomorrow():#用Date.tomorrow()的形式去產生實例,該實例用的是明天的時間 t=time.localtime(time.time()+86400) return Date(t.tm_year,t.tm_mon,t.tm_mday) a=Date('1987',11,27) #自己定義時間 b=Date.now() #采用當前時間 c=Date.tomorrow() #采用明天的時間 print(a.year,a.month,a.day) print(b.year,b.month,b.day) print(c.year,c.month,c.day) #分割線============================== import time class Date: def __init__(self,year,month,day): self.year=year self.month=month self.day=day @staticmethod def now(): t=time.localtime() return Date(t.tm_year,t.tm_mon,t.tm_mday) class EuroDate(Date): def __str__(self): return 'year:%s month:%s day:%s' %(self.year,self.month,self.day) e=EuroDate.now() print(e) #我們的意圖是想觸發EuroDate.__str__,但是結果為 ''' 輸出結果: <__main__.Date object at 0x1013f9d68> ''' 因為e就是用Date類產生的,所以根本不會觸發EuroDate.__str__,解決方法就是用classmethod import time class Date: def __init__(self,year,month,day): self.year=year self.month=month self.day=day # @staticmethod # def now(): # t=time.localtime() # return Date(t.tm_year,t.tm_mon,t.tm_mday) @classmethod #改成類方法 def now(cls): t=time.localtime() return cls(t.tm_year,t.tm_mon,t.tm_mday) #哪個類來調用,即用哪個類cls來實例化 class EuroDate(Date): def __str__(self): return 'year:%s month:%s day:%s' %(self.year,self.month,self.day) e=EuroDate.now() print(e) #我們的意圖是想觸發EuroDate.__str__,此時e就是由EuroDate產生的,所以會如我們所願 ''' 輸出結果: year:2017 month:3 day:3 '''