Python Class __div__ issue - python

The tuples represent fractions. I'm trying to divide the fractions by multiplying by the reciprical
class Test():
def __init__(self):
self._x=(1,2)
def __div__(self,div_fraction):
return (self._x[0]*div_fraction[1],self._x[1]*div_fraction[0])
y=Test()
z=y/(1,3)
print(z)
Gives me:
Traceback (most recent call last):
File "E:/test.py", line 8, in <module>
z=y/(1,3)
TypeError: unsupported operand type(s) for /: 'Test' and 'tuple'
Yet when I change the __div__ to __mul__ and use * instead of / it does what it should.
How do I fix the exception I'm getting?

Python 3.x uses __truediv__ and __floordiv__. __div__ is 2.x-only.

had the same problem the other day.
see if __future__.division is active in your environment. if so, you need to define __truediv__ as well.
http://docs.python.org/2/library/operator.html#mapping-operators-to-functions

Related

Unable to make built-in function 'sum' work for an array of objects of my class [duplicate]

In the sum function, the prototype is sum(iterable[,start]), which sums everything in the iterable object plus the start value. I wonder why there is a start value in here? Is there nay particular use case this value is needed?
Please don't give any more examples how start is used. I am wondering why it exist in this function. If the prototype of sum function is only sum(iterable), and return None if iterable is empty, everything will just work. So why we need start in here?
If you are summing things that aren't integers you may need to provide a start value to avoid an error.
>>> from datetime import timedelta
>>> timedeltas = [timedelta(1), timedelta(2)]
>>> sum(timedeltas)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
>>> sum(timedeltas, timedelta())
datetime.timedelta(3)

Python: Accidentally assigned repr an int value

I don't exactly know how I whiffed this, but at some point I input
repr = 64
into the python console in spyder. When I now try to run repr(b64) this happens:
repr(b64)
Traceback (most recent call last):
File "<ipython-input-23-8c64b01419a6>", line 1, in <module>
repr(b64)
TypeError: 'int' object is not callable
can I fix this without restarting spyder?
Delete your variable:
del repr
This will clear the binding you created, unhiding the builtin. (It will not remove the builtin repr.) This gets you back to a slightly cleaner state than repr = builtins.repr would, though it usually won't matter.
Use builtins.repr:
>>> repr = 42
>>> repr(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> from builtins import repr
>>> repr(42)
'42'
(or use del as suggested by user2357112).

In Python 3.x, TypeError: unsupported operand type(s) for /: 'complex' and 'complex' [duplicate]

The tuples represent fractions. I'm trying to divide the fractions by multiplying by the reciprical
class Test():
def __init__(self):
self._x=(1,2)
def __div__(self,div_fraction):
return (self._x[0]*div_fraction[1],self._x[1]*div_fraction[0])
y=Test()
z=y/(1,3)
print(z)
Gives me:
Traceback (most recent call last):
File "E:/test.py", line 8, in <module>
z=y/(1,3)
TypeError: unsupported operand type(s) for /: 'Test' and 'tuple'
Yet when I change the __div__ to __mul__ and use * instead of / it does what it should.
How do I fix the exception I'm getting?
Python 3.x uses __truediv__ and __floordiv__. __div__ is 2.x-only.
had the same problem the other day.
see if __future__.division is active in your environment. if so, you need to define __truediv__ as well.
http://docs.python.org/2/library/operator.html#mapping-operators-to-functions

When does python raise a FloatingPointError?

Python documentation says that FloatingPointError is raised when a float calculation fails. But what is exactly meant here by "a float calculation"?
I tried adding, multiplying and dividing with floats but never managed to raise this specific error. Instead, i got a TypeError:
10/'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Can someone help me understand when a FloatingPointError is raised in python?
It is part of the fpectl module. The FloatingPointError shouldn't be raised if you don't explicitly turn it on (fpectl.turnon_sigfpe()).
However mind the note:
The fpectl module is not built by default, and its usage is discouraged and may be dangerous except in the hands of experts. See also the section fpectl-limitations on limitations for more details.
Update: The fpectl module has been removed as of Python 3.7.
Even with FloatingPointErrors turned on, 10/'a' will never raise one. It will always raise a TypeError. A FloatingPointError will only be raised for operations that reach the point of actually performing floating-point math, like 1.0/0.0. 10/'a' doesn't get that far.
You can also trigger a FloatingPointError within numpy, by setting the appropriate numpy.seterr (or numpy.errstate context manager) flag. For an example taken from the documentation:
>>> np.sqrt(-1)
nan
>>> with np.errstate(invalid='raise'):
... np.sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt
Interestingly, it also raises FloatingPointError when all operands are integers:
>>> old_settings = np.seterr(all='warn', over='raise')
>>> np.int16(32000) * np.int16(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FloatingPointError: overflow encountered in short_scalars
The documentation notes the conditions under which the FloatingPointError will be raised:
The floating-point exceptions are defined in the IEEE 754 standard [1]:
Division by zero: infinite result obtained from finite numbers.
Overflow: result too large to be expressed.
Underflow: result so close to zero that some precision was lost.
Invalid operation: result is not an expressible number, typically indicates that a NaN was produced.

Dividing Fractions in Python 3 [duplicate]

The tuples represent fractions. I'm trying to divide the fractions by multiplying by the reciprical
class Test():
def __init__(self):
self._x=(1,2)
def __div__(self,div_fraction):
return (self._x[0]*div_fraction[1],self._x[1]*div_fraction[0])
y=Test()
z=y/(1,3)
print(z)
Gives me:
Traceback (most recent call last):
File "E:/test.py", line 8, in <module>
z=y/(1,3)
TypeError: unsupported operand type(s) for /: 'Test' and 'tuple'
Yet when I change the __div__ to __mul__ and use * instead of / it does what it should.
How do I fix the exception I'm getting?
Python 3.x uses __truediv__ and __floordiv__. __div__ is 2.x-only.
had the same problem the other day.
see if __future__.division is active in your environment. if so, you need to define __truediv__ as well.
http://docs.python.org/2/library/operator.html#mapping-operators-to-functions

Categories