I have been messing around with object instantiation. I don't understand why this is raising errors while returning its identity?
>>> class Complex:
... def __init__(self):
... print(f'Complex identity: {id(self)}' )
...
>>> a = Complex() * 27
Complex identity: 2660854434064
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'Complex' and 'int'
CodePudding user response:
This is actually happening because python objects are created before variable assignments. Multiplying a Complex instance will raise an exception and the variable a remained uncreated because of the exception on the right-hand side. But in the following example, the effect of creating a Complex instance is shown and the variable com is created, which is returning the memory address of the object. However, the variable a is not yet created. The variable on the left is bound to the object after the object is created on the right-hand side. Variables are just labels.
>>> com = Complex()
Complex identity: 2660854433008
>>> com
<__main__.Complex object at 0x0000026B874884F0>
>>> a = Complex() * 27
Complex identity: 2660854434064
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'Complex' and 'int'
>>> dir()
['Complex', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'com']
CodePudding user response:
You create an instance of a class and trying to multiply the instance with a number ,You want to do overloading of operations,see an example below how to do it the proper way with Points(You can adjust it to what you want to do with Complex number
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "<Point x:{0},y:{1}>".format(self.x, self.y)
# implement addition
def __add__(self, other):
return Point(self.x other.x, self.y other.y)
# implement subtraction
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
# implement in-place addition
def __iadd__(self, other):
self.x = other.x
self.y = other.y
return self
# Declare some points
p1 = Point(10, 20)
p2 = Point(30, 30)
print(p1, p2)
# Add two points
p3 = p1 p2
print(p3)
# subtract two points
p4 = p2 - p1
print(p4)
# Perform in-place addition
p1 = p2
print(p1)
CodePudding user response:
In the specific instance of what you've done you haven't created the appropriate dunder methods for your class:
class Complex:
def __init__(self, real, imaginary):
print(f'Complex identity: {id(self)}')
self.complex = f"{real} {imaginary}i"
self.real = real
self.imaginary = imaginary
def __mul__(self, input):
if isinstance(input, int): #Just an example error type
return f"{self.real*input} {self.imaginary*input}i"
else:
raise Exception("TypeError: Not complex, real or imaginary")
if __name__ == "__main__":
a = Complex(10,23)
print(a*10)