魔法方法
对象构造相关:new、init、del。
1 from os.path import join
2
3 class FileObject:
4 '''Wrapper for file objects to make sure the file gets closed on deletion.'''
5
6 def __init__(self, filepath='~', filename='sample.txt'):
7 # open a file filename in filepath in read and write mode
8 self.file = open(join(filepath, filename), 'r+')
9
10 def __del__(self):
11 self.file.close()
12 del self.file
运算符重载:所有运算符都能重载。
1 class Word(str):
2 '''Class for words, defining comparison based on word length.'''
3
4 def __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)
7 if ' ' in word:
8 print "Value contains spaces. Truncating to first space."
9 word = word[:word.index(' ')] # Word is now all chars before first space
10 return str.__new__(cls, word)
11
12 def __gt__(self, other):
13 return len(self) > len(other)
14
15 def __lt__(self, other):
16 return len(self) < len(other)
17
18 def __ge__(self, other):
19 return len(self) >= len(other)
20
21 def __le__(self, other):
22 return 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.
3 The counter increments each time the value is changed.'''
4
5 def __init__(self, value):
6 super(AccessCounter, self).__setattr__('counter', 0)
7 super(AccessCounter, self).__setattr__('value', value)
8
9 def __setattr__(self, name, value):
10 if name == 'value':
11 super(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)
14 super(AccessCounter, self).__setattr__(name, value)
15
16 def __delattr__(self, name):
17 if name == 'value':
18 super(AccessCounter, self).__setattr__('counter', self.counter + 1)
19 super(AccessCounter, self).__delattr__(name)
集合实现
1 class FunctionalList:
2 '''A class wrapping a list with some extra functional magic, like head,
3 tail, init, last, drop, and take.'''
4
5 def __init__(self, values=None):
6 if values is None:
7 self.values = []
8 else:
9 self.values = values
10
11 def __len__(self):
12 return len(self.values)
13
14 def __getitem__(self, key):
15 # if key is of invalid type or value, the list values will raise the error
16 return self.values[key]
17
18 def __setitem__(self, key, value):
19 self.values[key] = value
20
21 def __delitem__(self, key):
22 del self.values[key]
23
24 def __iter__(self):
25 return iter(self.values)
26
27 def __reversed__(self):
28 return FunctionalList(reversed(self.values))
29
30 def append(self, value):
31 self.values.append(value)
32 def head(self):
33 # get the first element
34 return self.values[0]
35 def tail(self):
36 # get all elements after the first
37 return self.values[1:]
38 def init(self):
39 # get elements up to the last
40 return self.values[:-1]
41 def last(self):
42 # get last element
43 return self.values[-1]
44 def drop(self, n):
45 # get all elements except first n
46 return self.values[n:]
47 def take(self, n):
48 # get first n elements
49 return self.values[:n]
可调用对象,像方法一样调用对象
1 class Entity:
2 '''Class to represent an entity. Callable to update the entity's position.'''
3
4 def __init__(self, size, x, y):
5 self.x, self.y = x, y
6 self.size = size
7
8 def __call__(self, x, y):
9 '''Change the position of the entity.'''
10 self.x, self.y = x, y
11 print(x, y)
12
13 entity = Entity(5, 1, 1)
14 entity(2, 2)
资源管理
1 class Closer:
2 def __enter__(self):
3 return self
4
5 def __exit__(self, exception_type, exception_val, trace):
6 print("清理完成")
7 return True;
8
9 with Closer() as closer:
10 pass
对象描述符
1 class Meter(object):
2 '''Descriptor for a meter.'''
3
4 def __init__(self, value=0.0):
5 self.value = float(value)
6 def __get__(self, instance, owner):
7 return self.value
8 def __set__(self, instance, value):
9 self.value = float(value)
10
11 class Foot(object):
12 '''Descriptor for a foot.'''
13
14 def __get__(self, instance, owner):
15 return instance.meter * 3.2808
16 def __set__(self, instance, value):
17 instance.meter = float(value) / 3.2808
18
19 class Distance(object):
20 '''Class to represent distance holding two descriptors for feet and
21 meters.'''
22 meter = Meter()
23 foot = Foot()
Mixin(也叫掺入)
掺入模块:playable.py
1 # coding=utf-8
2
3 def paly(self):
4 print("游戏中...")
掺入目标模块:test.py
1 #coding:utf-8
2
3 class TestClass:
4 def method1(self):
5 print("方法1")
6
7 def method2(self):
8 print("方法2")
9
10 TestClass.method2 = method2
11
12 test = TestClass()
13 test.method1() # 方法1
14 test.method2() # 方法2
Meta Programming(元编程)
1 TestClass = type("TestClass", (object,), {
2 "say": lambda self : print("你好啊")
3 })
4
5 test = TestClass()
6 test.say()
1 def getter(name):
2 def getterMethod(self):
3 return self.__getattribute__(name)
4 return getterMethod
5
6 def setter(name):
7 def setterMethod(self, value):
8 self.__setattr__(name, value)
9 return setterMethod
10
11 class TestClass:
12 getName = getter("name")
13 setName = setter("name")
14
15 test = TestClass()
16 test.setName("石浩阳")
17 print(test.getName())
网友评论