使用 修飾器+類 定義Python常量

原文地址: 使用 修飾器+類 定義Python常量 · Issue #13 · Chyroc/blog

起因

在一些函數中,我們有時候只想要指定的幾個輸入,但是在代碼/函數 交給別人使用的時候,別人還需要看文檔,甚至不知道該傳什麼值,這個有一點不友好。

所以,我們想在代碼中定義一些常量,供代碼使用者調用。

使用變數

# const.pyCAT = catDOG = dog

這個時候,我們就可以使用了

import constconst.CAT

嗯。。。。。這個時候,我們又有一個類型了

# const.pyCAT = catDOG = dogMAC = macWIN = windowsLINUX = linux

我們再來看一下

該選哪一個,CAT是什麼鬼?

使用類 + property

現在的常量代碼如下

# const.pyclass _Animal(object): @property def cat(self): return cat @property def dog(self): return dogclass _Platform(object): @property def mac(self): return mac @property def win(self): return windows @property def linux(self): return linuxAnimal = _Animal()Platform = _Platform()

使用:

嗯。。很好,現在有了剛剛吐槽的 分類 的功能。

不過有一天,有一個二貨改了你的常量!!!

const.Platform.mac = windows

你是不是是不是傻了?

不過這是不可能的,嘿嘿,因為沒有設置 @mac.setter修飾器的方法!

但是呢,這裡還有一個問題,就是這代碼也太長了吧,為了定義一個常量,需要3行代碼,假如有20個常量呢。。。不僅寫起來麻煩,看代碼也很煩啊!!

使用類修飾器

# const.pyclass _Platform(object): mac = mac windows = windows linux = linuxPlatform = _Platform()

代碼是減了不少,但是值可以改變。所以為了避免這樣的情況,需要給類加一個修飾器~

# const.pyfrom functools import wrapsdef Const(cls): @wraps(cls) def new_setattr(self, name, value): raise Exception(const : {} can not be changed.format(name)) cls.__setattr__ = new_setattr return cls@Constclass _Platform(object): mac = mac windows = windows linux = linuxPlatform = _Platform()

最終的代碼

# const.pyfrom functools import wrapsdef Const(cls): @wraps(cls) def new_setattr(self, name, value): raise Exception(const : {} can not be changed.format(name)) cls.__setattr__ = new_setattr return cls@Constclass _Animal(object): cat = cat dog = dog@Constclass _Platform(object): mac = mac windows = windows linux = linux@Constclass _Const(object): animal = _Animal() platform = _Platform()CONST = _Const()


推薦閱讀:

初學python可以閱讀哪些代碼?讀代碼時要做些什麼工作幫助提高?
如何實施代碼重構?
有大神說,0基礎學編程簡直是找虐,今天我想說你也可以!
Lombok指南
回顧—B 站第二屆彈幕大賽

TAG:Python | 代码 | 编程 |