def __abs__(self): return math.sqrt(sum(x * x for x in self)) def __neg__(self): return Vector(-x for x in self) #为了计算 -v,构建一个新 Vector 实例,把 self 的每个分量都取反 def __pos__(self): return Vector(self) #为了计算 +v,构建一个新 Vector 实例,传入 self 的各个分量
>>> import decimal
>>> ctx = decimal.getcontext() #获取当前全局算术运算符的上下文引用
>>> ctx.prec = 40 #把算术运算上下文的精度设为40
>>> one_third = decimal.Decimal('1') / decimal.Decimal('3') #使用当前精度计算1/3
>>> one_third
Decimal('0.3333333333333333333333333333333333333333') #查看结果,小数点后的40个数字
>>> one_third == +one_third #one_third = +one_thied返回TRUE
True
>>> ctx.prec = 28 #把精度降为28
>>> one_third == +one_third #one_third = +one_thied返回FalseFalse >>> +one_third Decimal('0.3333333333333333333333333333') #查看+one_third,小术后的28位数字
>>> from collections import Counter
>>> ct = Counter('abracadabra')
>>> ct['r'] = -3
>>> ct['d'] = 0
>>> ct
Counter({'a': 5, 'r': -3, 'b': 2, 'c': 1, 'd': 0})
>>> +ct
Counter({'a': 5, 'b': 2, 'c': 1})
>>> v1 = Vector([3, 4, 5]) >>> v2 = Vector([6, 7, 8]) >>> v1 + v2 Vector([9.0, 11.0, 13.0]) >>> v1 + v2 == Vector([3+6, 4+7, 5+8]) True
def __add__(self, other): pairs = itertools.zip_longest(self, other, fillvalue=0.0) #生成一个元祖,a来自self,b来自other,如果两个长度不够,通过fillvalue设置的补全值自动补全短的 return Vector(a + b for a, b in pairs) #使用生成器表达式计算pairs中的各个元素的和
# 在Vector类中定义 def __add__(self, other): pairs = itertools.zip_longest(self, other, fillvalue=0.0) #生成一个元祖,a来自self,b来自other,如果两个长度不够,通过fillvalue设置的补全值自动补全短的 return Vector(a + b for a, b in pairs) #使用生成器表达式计算pairs中的各个元素的和 def __radd__(self, other): #会直接委托给__add__ return self + other
>>> v1 = Vector([1, 2, 3]) >>> v1 * 10 Vector([10.0, 20.0, 30.0]) >>> 11 * v1 Vector([11.0, 22.0, 33.0])
def __mul__(self, scalar): if isinstance(scalar, numbers.Real): return Vector(n * scalar for n in self) else: return NotImplemented def __rmul__(self, scalar): return self * scalar
>>> va = Vector([1, 2, 3]) >>> vz = Vector([5, 6, 7]) >>> va @ vz == 38.0 # 1*5 + 2*6 + 3*7 True >>> [10, 20, 30] @ vz 380.0 >>> va @ 3 Traceback (most recent call last): ... TypeError: unsupported operand type(s) for @: 'Vector' and 'int'
>>> va = Vector([1, 2, 3]) >>> vz = Vector([5, 6, 7]) >>> va @ vz == 38.0 # 1*5 + 2*6 + 3*7 True >>> [10, 20, 30] @ vz 380.0 >>> va @ 3 Traceback (most recent call last): ... TypeError: unsupported operand type(s) for @: 'Vector' and 'int'
|
分组 |
中缀运算符 | 正向方法调用 | 反向方法调用 | 后备机制 |
| 相等性 | a == b | a.__eq__(b) | b.__eq__(a) | 返回 id(a) == id(b) |
| a != b | a.__ne__(b) | b.__ne__(a) | 返回 not (a == b) | |
| 排序 | a > b | a.__gt__(b) | b.__lt__(a) | 抛出 TypeError |
| a < b | a.__lt__(b) | b.__gt__(a) | 抛出 TypeError | |
| a >= b | a.__ge__(b) | b.__le__(a) | 抛出 TypeError | |
| a <= b | a.__le__(b) | b.__ge__(a) | 抛出T ypeError |
from array import array
import reprlib
import math
import numbers
import functools
import operator
import itertools
class Vector:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('['):-1]
return 'Vector({})'.format(components)
def __str__(self):
return str(tuple(self))
def __bytes__(self):
return (bytes([ord(self.typecode)]) + bytes(self._components))
def __eq__(self, other):
return (len(self) == len(other) and all(a == b for a, b in zip(self, other)))
def __hash__(self):
hashes = map(hash, self._components)
return functools.reduce(operator.xor, hashes, 0)
def __add__(self, other):
pairs = itertools.zip_longest(self, other, fillvalue=0.0) #生成一个元祖,a来自self,b来自other,如果两个长度不够,通过fillvalue设置的补全值自动补全短的
return Vector(a + b for a, b in pairs) #使用生成器表达式计算pairs中的各个元素的和
def __radd__(self, other): #会直接委托给__add__
return self + other
def __mul__(self, scalar):
if isinstance(scalar, numbers.Real):
return Vector(n * scalar for n in self)
else:
return NotImplemented
def __rmul__(self, scalar):
return self * scalar
def __matmul__(self, other):
try:
return sum(a * b for a, b in zip(self, other))
except TypeError:
return NotImplemented
def __rmatmul__(self, other):
return self @ other
def __abs__(self):
return math.sqrt(sum(x * x for x in self))
def __neg__(self):
return Vector(-x for x in self) #为了计算 -v,构建一个新 Vector 实例,把 self 的每个分量都取反
def __pos__(self):
return Vector(self) #为了计算 +v,构建一个新 Vector 实例,传入 self 的各个分量
def __bool__(self):
return bool(abs(self))
def __len__(self):
return len(self._components)
def __getitem__(self, index):
cls = type(self)
if isinstance(index, slice):
return cls(self._components[index])
elif isinstance(index, numbers.Integral):
return self._components[index]
else:
msg = '{.__name__} indices must be integers'
raise TypeError(msg.format(cls))
shorcut_names = 'xyzt'
def __getattr__(self, name):
cls = type(self)
if len(name) == 1:
pos = cls.shorcut_names.find(name)
if 0 <= pos < len(self._components):
return self._components[pos]
msg = '{.__name__!r} object has no attribute {!r}'
raise AttributeError(msg.format(cls, name))
def angle(self, n):
r = math.sqrt(sum(x * x for x in self[n:]))
a = math.atan2(r, self[n-1])
if (n == len(self) - 1 ) and (self[-1] < 0):
return math.pi * 2 - a
else:
return a
def angles(self):
return (self.angle(n) for n in range(1, len(self)))
def __format__(self, fmt_spec=''):
if fmt_spec.endswith('h'):
fmt_spec = fmt_spec[:-1]
coords = itertools.chain([abs(self)], self.angles())
outer_fmt = '<{}>'
else:
coords = self
outer_fmt = '({})'
components = (format(c, fmt_spec) for c in coords)
return outer_fmt.format(', '.join(components))
@classmethod
def frombytes(cls, octets):
typecode = chr(octets[0])
memv = memoryview(octets[1:]).cast(typecode)
return cls(memv)
va = Vector([1.0, 2.0, 3.0])
vb = Vector(range(1, 4))
print('va == vb:', va == vb) #两个具有相同数值分量的 Vector 实例是相等的
t3 = (1, 2, 3)
print('va == t3:', va == t3)
print('[1, 2] == (1, 2):', [1, 2] == (1, 2))
va == vb: True va == t3: True [1, 2] == (1, 2): False
def __eq__(self, other):
if isinstance(other, Vector): #判断对比的是否和Vector同属一个实例
return (len(self) == len(other) and all(a == b for a, b in zip(self, other)))
else:
return NotImplemented #否则,返回NotImplemented
>>> va = Vector([1.0, 2.0, 3.0]) >>> vb = Vector(range(1, 4)) >>> va == vb True >>> t3 = (1, 2, 3) >>> va == t3 False
>>> v1 = Vector([1, 2, 3]) >>> v1_alias = v1 # 复制一份,供后面审查Vector([1, 2, 3])对象 >>> id(v1) # 记住一开始绑定给v1的Vector实例的ID >>> v1 += Vector([4, 5, 6]) # 增量加法运算 >>> v1 # 结果与预期相符 Vector([5.0, 7.0, 9.0]) >>> id(v1) # 但是创建了新的Vector实例 >>> v1_alias # 审查v1_alias,确认原来的Vector实例没被修改 Vector([1.0, 2.0, 3.0]) >>> v1 *= 11 # 增量乘法运算 >>> v1 # 同样,结果与预期相符,但是创建了新的Vector实例 Vector([55.0, 77.0, 99.0]) >>> id(v1)
from array import array
import reprlib
import math
import numbers
import functools
import operator
import itertools
class Vector:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('['):-1]
return 'Vector({})'.format(components)
def __str__(self):
return str(tuple(self))
def __bytes__(self):
return (bytes([ord(self.typecode)]) + bytes(self._components))
def __eq__(self, other):
if isinstance(other, Vector):
return (len(self) == len(other) and all(a == b for a, b in zip(self, other)))
else:
return NotImplemented
def __hash__(self):
hashes = map(hash, self._components)
return functools.reduce(operator.xor, hashes, 0)
def __add__(self, other):
pairs = itertools.zip_longest(self, other, fillvalue=0.0)
return Vector(a + b for a, b in pairs)
def __radd__(self, other):
return self + other
def __mul__(self, scalar):
if isinstance(scalar, numbers.Real):
return Vector(n * scalar for n in self)
else:
return NotImplemented
def __rmul__(self, scalar):
return self * scalar
def __matmul__(self, other):
try:
return sum(a * b for a, b in zip(self, other))
except TypeError:
return NotImplemented
def __rmatmul__(self, other):
return self @ other
def __abs__(self):
return math.sqrt(sum(x * x for x in self))
def __neg__(self):
return Vector(-x for x in self)
def __pos__(self):
return Vector(self)
def __bool__(self):
return bool(abs(self))
def __len__(self):
return len(self._components)
def __getitem__(self, index):
cls = type(self)
if isinstance(index, slice):
return cls(self._components[index])
elif isinstance(index, numbers.Integral):
return self._components[index]
else:
msg = '{.__name__} indices must be integers'
raise TypeError(msg.format(cls))
shorcut_names = 'xyzt'
def __getattr__(self, name):
cls = type(self)
if len(name) == 1:
pos = cls.shorcut_names.find(name)
if 0 <= pos < len(self._components):
return self._components[pos]
msg = '{.__name__!r} object has no attribute {!r}'
raise AttributeError(msg.format(cls, name))
def angle(self, n):
r = math.sqrt(sum(x * x for x in self[n:]))
a = math.atan2(r, self[n-1])
if (n == len(self) - 1 ) and (self[-1] < 0):
return math.pi * 2 - a
else:
return a
def angles(self):
return (self.angle(n) for n in range(1, len(self)))
def __format__(self, fmt_spec=''):
if fmt_spec.endswith('h'):
fmt_spec = fmt_spec[:-1]
coords = itertools.chain([abs(self)], self.angles())
outer_fmt = '<{}>'
else:
coords = self
outer_fmt = '({})'
components = (format(c, fmt_spec) for c in coords)
return outer_fmt.format(', '.join(components))
@classmethod
def frombytes(cls, octets):
typecode = chr(octets[0])
memv = memoryview(octets[1:]).cast(typecode)
return cls(memv)
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有