Python學習之定製類

來源:互聯網
上載者:User

標籤:

本文和大家分享的主要是 python開發中定製類的相關內容,一起來看看吧,希望對大家學習和使用這部分內容有所協助。 1. python中什麼是特殊方法任何資料類型的執行個體都有一個特殊方法:  __str__()·  用於 print 的  __str__·  用於 len 的  __len__·  用於 cmp 的  __cmp__·  特殊方法定義在 class 中·  不需要直接調用· Python 的某些函數或操作符會調用對應的特殊方法file:///C:\Users\wlc\AppData\Local\Temp\ksohtml\wps8B49.tmp.jpg     正確實現特殊方法·  只需要編寫用到的特殊方法·  有關聯性的特殊方法都必須實現·  __getattr__ ,  __setattr__ ,  __delattr__ 2. python中 __str__和__repr__ class  Person(object): def  __init__(self, name, gender):self.name = nameself.gender = gender class  Student(Person): def  __init__(self, name, gender, score):super(Student, self).__init__(name, gender)self.score = score def  __str__(self): return ’(Student: %s, %s, %s)’ % (self.name, self.gender, self.score)__repr__ = __str__s = Student(’Bob’, ’male’, 88) print s 3. python中 __cmp__對 int 、 str  等內建資料類型排序時, Python 的  sorted()  按照預設的比較函數  cmp  排序,但是,如果對一組  Student  類的執行個體排序時,就必須提供我們自己的特殊方法  __cmp__() class  Student(object): def  __init__(self, name, score):self.name = nameself.score = score def  __str__(self): return ’(%s: %s)’ % (self.name, self.score)__repr__ = __str__ def  __cmp__(self, s): if self.name < s.name: return -1 elif self.name > s.name: return 1 else: return 0 class  Student(object): def  __init__(self, name, score):self.name = nameself.score = score def  __str__(self): return ’(%s: %s)’ % (self.name, self.score)__repr__ = __str__ def  __cmp__(self, s): if self.score == s.score: return cmp(self.name, s.name) return -cmp(self.score, s.score)L = [Student(’Tim’, 99), Student(’Bob’, 88), Student(’Alice’, 99)] print sorted(L) 4. python中 __len__如果一個類表現得像一個list ,要擷取有多少個元素,就得用  len()  函數 .要讓 len()  函數工作正常,類必須提供一個特殊方法 __len__() ,它返回元素的個數。 class  Students(object): def  __init__(self, *args):self.names = args def  __len__(self): return len(self.names)ss = Students(’Bob’, ’Alice’, ’Tim’) print len(ss) # 3 class  Fib(object): def  __init__(self, num):a, b, L = 0, 1, [] for n  in range(num):L.append(a)a, b = b, a + bself.num = L def  __len__(self): return len(self.num)f = Fib(10) print f.num # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] print len(f) # 10 5. python中數學運算Python  提供的基礎資料型別 (Elementary Data Type)  int 、 float  可以做整數和浮點的四則運算以及乘方等運算。 def  gcd(a, b): if b == 0: return a return gcd(b, a % b) class  Rational(object): def  __init__(self, p, q):self.p = pself.q = q def  __add__(self, r): return Rational(self.p * r.q + self.q * r.p, self.q * r.q) def  __sub__(self, r): return Rational(self.p * r.q - self.q * r.p, self.q * r.q) def  __mul__(self, r): return Rational(self.p * r.p, self.q * r.q) def  __div__(self, r): return Rational(self.p * r.q, self.q * r.p) def  __str__(self):g = gcd(self.p, self.q) return ’%s/%s’ % (self.p / g, self.q / g)__repr__ = __str__r1 = Rational(1, 2)r2 = Rational(1, 4) print r1 + r2 print r1 - r2 print r1 * r2 print r1 / r2 6. python中類型轉換 print int(12.34) # 12 print float(12) # 12.0 class  Rational(object): def  __init__(self, p, q):self.p = pself.q = q def  __int__(self): return self.p // self.q def  __float__(self): return float(self.p) / self.q print float(Rational(7, 2)) # 3.5 print float(Rational(1, 3)) # 0.333333333333 7. python中 @property class  Student(object): def  __init__(self, name, score):self.name = nameself.__score = score@property def  score(self): return self.__score@score.setter def  score(self, score): if score < 0  or score > 100: raise ValueError(’invalid score’)self.__score = score@property def  grade(self): if self.score < 60: return ’C’ if self.score < 80: return ’B’ return ’A’s = Student(’Bob’, 59) print s.grades.score = 60 print s.grades.score = 99 print s.grade 8. python中 __slots__slots 的目的是限制當前類所能擁有的屬性,如果不需要添加任意動態屬性,使用 __slots__ 也能節省記憶體。 class  Student(object):__slots__ = (’name’, ’gender’, ’score’) def  __init__(self, name, gender, score):self.name = nameself.gender = genderself.score = scores = Student(’Bob’, ’male’, 59)s.name = ’Tim’ # OKs.score = 99 # OKs.grade = ’A’ # Error class  Person(object):__slots__ = (’name’, ’gender’) def  __init__(self, name, gender):self.name = nameself.gender = gender class  Student(Person):__slots__ = {’score’} def  __init__(self, name, gender, score):super(Student, self).__init__(name, gender)self.score = scores = Student(’Bob’, ’male’, 59)s.name = ’Tim’s.score = 99 print s.score 9. python中 __call__一個類執行個體也可以變成一個可調用對象,只需要實現一個特殊方法  __call__() class  Person(object): def  __init__(self, name, gender):self.name = nameself.gender = gender def  __call__(self, friend): print ’My name is %s...’ % self.name print ’My friend is %s...’ % friendp = Person(’Bob’, ’male’)p(’Tim’) # My name is Bob... My friend is Tim... class  Fib(object): def  __call__(self, num):a, b, L = 0, 1, [] for n  in range(num):L.append(a)a, b = b, a + b return Lf = Fib() print f(10) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]來源: 部落格園

Python學習之定製類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.