新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python的attrs表示什么
attr可看作是一個類裝飾器但又不僅僅是簡單的裝飾器,他使得我們編寫類變得更加簡單輕松。下面先通過一個簡單的例子來見識下attr的強大吧。
現(xiàn)在我們需要編寫一個類,有a,b,c兩個屬性,正常的寫法:

class A(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c
看起來也沒那么復雜嘛。好了,現(xià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)
雖然看起來有點復雜,但是借助total_ordering,也算是以盡量少的代碼實現(xiàn)了所需功能了吧。
但是,有沒有更簡潔的方式呢?讓我們來看看借助于attr的實現(xiàn):
import attr @attr.sclass A(object): a = attr.ib() b = attr.ib()
更多學習內容,請點擊Python學習網(wǎng)。
文章標題:創(chuàng)新互聯(lián)Python教程:python的attrs表示什么
文章來源:http://www.dlmjj.cn/article/cceeded.html


咨詢
建站咨詢
