新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:python的attrs表示什么
attr可看作是一個(gè)類裝飾器但又不僅僅是簡(jiǎn)單的裝飾器,他使得我們編寫類變得更加簡(jiǎn)單輕松。下面先通過(guò)一個(gè)簡(jiǎn)單的例子來(lái)見識(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
看起來(lái)也沒那么復(fù)雜嘛。好了,現(xiàn)在領(lǐng)導(dǎo)說(shuō)類的打印輸出不好看,又不能進(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)
雖然看起來(lái)有點(diǎn)復(fù)雜,但是借助total_ordering,也算是以盡量少的代碼實(shí)現(xiàn)了所需功能了吧。
但是,有沒有更簡(jiǎn)潔的方式呢?讓我們來(lái)看看借助于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)。
分享標(biāo)題:創(chuàng)新互聯(lián)Python教程:python的attrs表示什么
本文URL:http://m.fisionsoft.com.cn/article/cceeded.html


咨詢
建站咨詢
