1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| class Vector(object): def __new__(cls, *args, **kwargs): print("call __new__") return object.__new__(cls, *args, **kwargs)
def __init__(self, x, y): self.x = x self.y = y self.uid = x + y
def __str__(self): return 'x: %s, y: %s' % (self.x, self.y)
def __repr__(self): return 'Vector(%s, %s)' % (self.x, self.y)
def __add__(self, other): return Vector(self.x+other.x, self.y+other.y)
def __call__(self): print('Called by myself!')
def __del__(self): self.conn.close()
def __getattr__(self, name): if name == 'adult': if self.age > 1.0: return 1 else: return False else: raise AttributeError(name)
def __setattr__(self, key, value): super(Vector, self).__setattr__(key, value)
def __delattr__(self, key): super(Vector, self).__delattr__(key)
def __getattribute__(self, key): """访问任意属性/方法都首先经过这里""" if key == 'hello': return self.say if key == 'world': raise AttributeError
return super(Vector, self).__getattribute__(key)
def say(self): return 'hello'
def __hash__(self): return self.uid
def __eq__(self, other): return self.uid == other.uid
v1 = Vector(1, 1) print(v1)
v2 = Vector(2, 2) print(v1 + v2)
v2()
|