Python学习总结( 五 )
魔法方法详细内容参考: 。
对象构造相关:__new__、__init__、__del__ 。
1 from os.path import join 23 class FileObject: 4'''Wrapper for file objects to make sure the file gets closed on deletion.''' 56def __init__(self, filepath='~', filename='sample.txt'): 7# open a file filename in filepath in read and write mode 8self.file = open(join(filepath, filename), 'r+') 9 10def __del__(self):11self.file.close()12del self.file
运算符重载:所有运算符都能重载 。
1 class Word(str): 2'''Class for words, defining comparison based on word length.''' 34def __new__(cls, word): 5# Note that we have to use __new__. This is because str is an immutable 6# type, so we have to initialize it early (at creation) 7if ' ' in word: 8print "Value contains spaces. Truncating to first space." 9word = word[:word.index(' ')] # Word is now all chars before first space10return str.__new__(cls, word)11 12def __gt__(self, other):13return len(self) > len(other)14 15def __lt__(self, other):16return len(self) < len(other)17 18def __ge__(self, other):19return len(self) >= len(other)20 21def __le__(self, other):22return len(self) <= len(other)23 24 print(Word("duan") > Word("wei"))
属性访问 。
1 class AccessCounter: 2'''A class that contains a value and implements an access counter. 3The counter increments each time the value is changed.''' 45def __init__(self, value): 6super(AccessCounter, self).__setattr__('counter', 0) 7super(AccessCounter, self).__setattr__('value', value) 89def __setattr__(self, name, value):10if name == 'value':11super(AccessCounter, self).__setattr__('counter', self.counter + 1)12# Make this unconditional.13# If you want to prevent other attributes to be set, raise AttributeError(name)14super(AccessCounter, self).__setattr__(name, value)15 16def __delattr__(self, name):17if name == 'value':18super(AccessCounter, self).__setattr__('counter', self.counter + 1)19super(AccessCounter, self).__delattr__(name)
集合实现 。
1 class FunctionalList: 2'''A class wrapping a list with some extra functional magic, like head, 3tail, init, last, drop, and take.''' 45def __init__(self, values=None): 6if values is None: 7self.values = [] 8else: 9self.values = values10 11def __len__(self):12return len(self.values)13 14def __getitem__(self, key):15# if key is of invalid type or value, the list values will raise the error16return self.values[key]17 18def __setitem__(self, key, value):19self.values[key] = value20 21def __delitem__(self, key):22del self.values[key]23 24def __iter__(self):25return iter(self.values)26 27def __reversed__(self):28return FunctionalList(reversed(self.values))29 30def append(self, value):31self.values.append(value)32def head(self):33# get the first element34return self.values[0]35def tail(self):36# get all elements after the first37return self.values[1:]38def init(self):39# get elements up to the last40return self.values[:-1]41def last(self):42# get last element43return self.values[-1]44def drop(self, n):45# get all elements except first n46return self.values[n:]47def take(self, n):48# get first n elements49return self.values[:n]
推荐阅读
- 计算机专业大一下学期,该选择学习Java还是Python
- 假期弯道超车 国美学习“神器”助孩子变身“学霸”
- 想自学Python来开发爬虫,需要按照哪几个阶段制定学习计划
- 未来想进入AI领域,该学习Python还是Java大数据开发
- Google AI建立了一个能够分析烘焙食谱的机器学习模型
- 学习大数据是否需要学习JavaEE
- 学习“时代楷模”精神 信息科技创新助跑5G智慧港口
- 2021年Java和Python的应用趋势会有什么变化?
- 非计算机专业的本科生,想利用寒假学习Python,该怎么入手
- 用Python制作图片验证码,这三行代码完事儿