"Python" "Overloaded operator"

Source: Internet
Author: User
Tags abs

#
#例子13-3 unary operator + get a new counter instance, but no 0 value and negative counter
From collections Import Counter

ct = Counter (' Abracadabra ')
print (CT) #Counter ({' A ': 5, ' R ': 2, ' B ': 2, ' C ': 1, ' d ': 1})
Ct[' r '] = 3
ct[' d '] = 0
print (CT) #Counter ({' A ': 5, ' B ': 2, ' C ': 1, ' d ': 0, ' R ':-3})
Print (+CT) #Counter ({' A ': 5, ' B ': 2, ' C ': 1})


Import Itertools
A = (a)
b = [4,5]
D = itertools.zip_longest (a,b,fillvalue=0.0)






#以下是Vector




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 = (hash (x) for x in self)
Return Functools.reduce (Operator.xor, hashes, 0)

def __abs__ (self):
return math.sqrt (SUM (x * x for X, 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))

Shortcut_names = ' Xyzt '

def __getattr__ (self, name):
CLS = Type (self)
If len (name) = = 1:
pos = cls.shortcut_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): # <2>
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): # <3>
Return (Self.angle (n) for n in range (1, Len (self))

def __format__ (self, fmt_spec= "):
If Fmt_spec.endswith (' H '): # hyperspherical coordinates
Fmt_spec = Fmt_spec[:-1]
coords = Itertools.chain ([ABS (self)],
Self.angles ()) # <4>
outer_fmt = ' <{}> ' # <5>
Else
coords = Self
Outer_fmt = ' ({}) ' # <6>
components = (format (c, fmt_spec) for C in coords) # <7>
Return Outer_fmt.format (', '. Join (components)) # <8>

@classmethod
Def frombytes (CLS, octets):
TypeCode = Chr (Octets[0])
MEMV = Memoryview (octets[1:]). CAST (TypeCode)
Return CLS (MEMV)
‘‘‘
def __add__ (self, Other):
Pairs = Itertools.zip_longest (self,other,fillvalue=0.0)
Return Vector (A+b for a, b in pairs)
#print ((3,40) + v1) #TypeError: can only concatenate a tuple (not "Vector") to a tuple "parse" if the left operand is an object other than the Vector, it cannot be processed
#... To support different types of operations, Python provides special allocation mechanisms for infix operator special methods. For an expression a+b, the interpreter performs the following steps
#... (1) If A has a __add__ method and the return value is not notimplemented, call a.__add__ (b) and return the result
#... (2) If a does not have a __add__ method, or calls the __add__ method to return notimplemented, check that B has no __radd__ method, if any, and does not return notimplemented, call b.__radd__ (a), And then return the result
#... (3) If the first two conditions are not satisfied, throw typeerror and indicate in the error message that the operand type does not support
#[note] Don't confuse notimplemented notimplementederror. The former is a special singleton value, and if the infix operator special method cannot handle the given operand, it is returned to the interpreter. The latter is an exception, and the placeholder method in the abstract class throws it (raise), reminding the subclass that it must overwrite
‘‘‘
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 #__radd__通常就这么简单: Call the appropriate operator directly, and __add__ is delegated here. Any commutative operator can be so left. When working with numbers and vectors, + can be swapped, but not when stitching sequences
#例子13-8 The operand key of the vector.__add__ method if the object can be iterated
V2 = Vector ([3,4,5])
#print (v2 + 1) #TypeError: zip_longest argument #2 must support iteration
#例子13 9 Operand of this addition should be an iterative numeric object
Print (v2 + ' ABC ') #TypeError: unsupported operand type (s) for +: ' float ' and ' str '
#例子13-10 for 13-8 13-9 need to be optimized again, that is, there are errors to throw

V1 = Vector ([3,4,5])
Print (v1 + (10,20)) # (13.0, 24.0, 5.0)


"Python" "Overloaded operator"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.