掃二維碼與項(xiàng)目經(jīng)理溝通
我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
attr可看作是一個(gè)類裝飾器但又不僅僅是簡(jiǎn)單的裝飾器,他使得我們編寫類變得更加簡(jiǎn)單輕松。下面先通過一個(gè)簡(jiǎn)單的例子來見識(shí)下attr的強(qiáng)大吧。
現(xiàn)在我們需要編寫一個(gè)類,有a,b,c兩個(gè)屬性,正常的寫法:

class A(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c
看起來也沒那么復(fù)雜嘛。好了,現(xiàn)在領(lǐng)導(dǎo)說類的打印輸出不好看,又不能進(jìn)行比較,行吧,有需求就加吧。
from functools import total_ordering@total_orderingclass A(object):
def __init__(self, a, b, c):
self.a = a self.b = b def __repr__(self):
return "ArtisanalClass(a={}, b={})".format(self.a, self.b)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (self.a, self.b) == (other.a, other.b)
def __lt__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (self.a, self.b) < (other.a, other.b)
雖然看起來有點(diǎn)復(fù)雜,但是借助total_ordering,也算是以盡量少的代碼實(shí)現(xiàn)了所需功能了吧。
但是,有沒有更簡(jiǎn)潔的方式呢?讓我們來看看借助于attr的實(shí)現(xiàn):
import attr @attr.sclass A(object): a = attr.ib() b = attr.ib()
更多學(xué)習(xí)內(nèi)容,請(qǐng)點(diǎn)擊Python學(xué)習(xí)網(wǎng)。

我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流