So the task is to make a universal Vector class to perform add method whatever(str or int) the x,y values are.
So here is the code that i've tried to execute just to check if try,except somehow works inside a class
class Vector():
def __init__(self,x,y):
self.x = x
self.y = y
def __valuecheck__(self):
try:
self.x + "a"
except TypeError:
return str(self.x)
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return "Vector({},{})".format(self.x,self.y)
a = Vector(1,"a")
b = Vector("a",2)
c = a.__add__(b)
print(c)
The expected output is
Vector(1a,a2)
I've tried different variants, defining classic function e.g. def valuecheck(), as well tried adding try,except to add and init method, but none seem to work. Need your help guys, any tip is very appreciated!
Cheers!
I think I have found the answer.
class Vector():
def __init__(self,x,y):
self.x = x
self.y = y
def __valuecheck__(self):
try:
self.x + "a"
except TypeError:
return str(self.x)
def __repr__(self):
return "Vector({},{})".format(self.x,self.y)
def __add__(self, other):
mvbh = str(self.x), str(self.y) # My Vector Before Hand
myVector = ''.join(mvbh)
ovbh = str(other.x), str(other.y) # Other Vector Before Hand
otherVector = ''.join(ovbh)
final = "Vector({}, {})".format(myVector, otherVector) # Change this to create a new vector
print(final)
a = Vector(1,"a")
b = Vector("a",2)
a.__add__(b)
class Vector():
def __init__(self,x,y):
self.x = x
self.y = y
def __valuecheck__(self):
try:
self.x + "a"
except TypeError:
return str(self.x)
def __add__(self, other):
return Vector(str(self.x) + str(other.x), str(self.y) + str(other.y))
def __repr__(self):
return "Vector({},{})".format(self.x,self.y)
a = Vector(1,"a")
b = Vector("a",2)
c = a.__add__(b)
print(c)
Related
I want to run this code (must) including the attribute value next to total in the print section. What code should I insert inside the class to do it?
class Random:
def __init__(self, x):
self.x = x
def __add__(self, other):
return self.x + other.x
p1 = Random(2)
p2 = Random(3)
total = p1 + p2
print(total.value)
Return an instance of Random in your __add__ method and add a property with the name value for the class.
class Random:
def __init__(self, x):
self.x = x
def __add__(self, other):
return Random(self.x + other.x)
#property
def value(self):
return self.x
p1 = Random(2)
p2 = Random(3)
total = p1 + p2
print(total.value)
Of course the better option would be to replace the instance attribute x with value. Then there's no need for the property.
class Random:
def __init__(self, x):
self.value = x
def __add__(self, other):
return Random(self.value + other.value)
Make total a Random as well.
class Random:
def __init__(self, value):
self.value = value
def __add__(self, other):
return Random(self.value + other.value)
p1: Random = Random(2)
p2: Random = Random(3)
total: Random = p1 + p2
print(total.value)
I am working on a class that has attributes depending from one another.
When instantiated, the class should try to initiate all the attributes it can but is should skip the ones raising an exception.
Something like this:
def foo:
def __init__(self, a, b, c):
try: self.x = len(a)
except: pass
try: self.y = sum(b)
except: pass
try: self.z = c
except: pass
try: self.v = self.x + self.z
except: pass
try: self.w = self.x + self.y
except: pass
This works but it looks horrible.
Is there a way to simplify this process?
Is there a way to achieve the same result with a cleaner code like the following?
def foo:
def __init__(self, a, b, c):
try:
self.x = len(a)
self.y = sum(b)
self.z = c
self.v = self.x + self.z
self.w = self.x + self.y
except:
continue_to_the_next_line()
class Point(object):
''' A point on a grid at location x, y '''
def __init__(self, x, y):
self.X=x
self.Y=y
def __str__(self):
return "X=" + str(self.X), "Y=" + str(self.Y)
def __add__(self, other):
if not isinstance(other, Point):
raise TypeError("must be of type point")
x= self.X+ other.X
y= self.Y+ other.Y
return Point(x, y)
p1= Point(5, 8)
print p1 + [10, 12]
When trying to add list or tuple at RHS i.e. print p1 + [10, 12], I'm getting
attributeError: int object has no attribute
How can this problem be solved?
First of all I can't reproduce the exact error you show, but I believe that is some sort of a "typo". You are trying to add a list instance to a Point instance, while the __add__ method of the later throws the error whenever you try to add anything that is not a Point instance.
def __add__(self, other):
if not isinstance(other, Point):
raise TypeError("must be of type point")
You could possibly overcome it by adding a fair bit of polymorphism.
from collections import Sequence
class Point(object):
...
def _add(self, other):
x = self.X + other.X
y = self.Y + other.Y
return Point(x, y)
def __add__(self, other):
if isinstance(other, type(self)):
return self._add(other)
elif isinstance(other, Sequence) and len(other) == 2:
return self._add(type(self)(*other))
raise TypeError("must be of type point or a Sequence of length 2")
You may have a comma instead of a plus. Look at
def __str__(self):
return "X=" + str(self.X), "Y=" + str(self.Y)
Which should be
def __str__(self):
return "X=" + str(self.X) + ", Y=" + str(self.Y)
At least on python3 when I correct it your code runs nicely. Obviously using print(p1 + Point(10,12)).
I've got a lesson doubt. Here is the objective from the class exercise:
Objective: Define a Python class V2, which represents two-dimensional vectors and supports the following operations:
Create a new vector out of two real numbers: v = V2(1.1, 2.2)
Convert a vector to a string (with the __str__ method)
Access the components (with the getX and getY methods)
Add two V2s to get a new V2 (with add and __add__ methods)
Multiply a V2 by a scalar (real or int) and return a new V2 (with the mul
and __mul__ methods)
Further information is given here:
Step 3. Define the add and mul methods, so that you get the following behavior:
>>> a = V2(1.0, 2.0)
>>> b = V2(2.2, 3.3)
>>> print a.add(b)
V2[3.2, 5.3]
>>> print a.mul(2)
V2[2.0, 4.0]
>>> print a.add(b).mul(-1)
V2[-3.2, -5.3]
Here is what I've been able to code:
class V2:
def __init__(self, x, y):
self.vector = [x, y]
self.x = x
self.y = y
def __str__(self):
return 'V2[' + str(self.x) + ', ' + str(self.y) + ']'
def __add__(self, other):
return 'V2[' + str(self.x + other.x) + ', ' + str(self.y + other.y) + ']'
def add(self, other):
return 'V2[' + str(self.x + other.x) + ', ' + str(self.y + other.y) + ']'
def __mul__(self, y):
return 'V2[' + str(self.x * y) + ', ' + str(self.y * y) + ']'
def mul(self, y):
return 'V2[' + str(self.x * y) + ', ' + str(self.y * y) + ']'
def getX(self):
return self.x
def getY(self):
return self.y
My question is how can I get print a.add(b)mul(-1) right? When I try to run this:
>>> p1 = V2(3, 2)
>>> p2 = V2(2, 3)
>>> p1.add(p2).mul(-1)
This error shows:
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
p1.add(p2).mul(-1)
AttributeError: 'str' object has no attribute 'mul'
I think I understand the error but I can't come up with a different way to do the add and mul methods without messing up other methods.
You need to create another instance of your class instead of a string:
def __add__(self, v):
return self.__class__(self.x + v.x, self.y + v.y)
def __mul__(self, n):
return self.__class__(self.x * n, self.y * n)
You can then use def add(self, v): return self + v. You might switch those, so that add() is the main method, and __add__ calls add.
The issue is that in each of your methods you are returning a string. You can't do any arithmetic with a string.Currently, your add method returns a string which then you call mul on (e.g. "[v1 3 4]".mul).
Change your add and mult method to the following where you return a V2.
def __add__(self, other):
return V2(self.x + other.x,self.y * other.y)
def __mul__(self, ascalar):
return V2(self.x * ascalar, self.y * ascalar)
In your methods, you are returning strings, instead of new instances of V2. So it should be:
class V2:
def __init__(self, x, y):
self.vector = [x, y]
self.x = x
self.y = y
def __str__(self):
return 'V2[' + str(self.x) + ', ' + str(self.y) + ']'
def __add__(self, other):
return V2(self.x + other.x, self.y + other.y)
def __mul__(self, c):
return V2(self.x * c ,self.y * c)
def getX(self):
return self.x
def getY(self):
return self.y
for example
def __str__ (self):
return (x,y)
def main():
how do u print the value of x and y from the def str(self): function
Would really appreciate it thanks!!!
That code doesn't make sense, so I'm extrapolating.
I'm assuming you have some class like so:
class Foobar(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return str((x,y))
def main():
foobar = Foobar(1,2)
main()
In this case, you COULD use string manipulation to handle it.
x_value, y_value = map(str.strip("()"), str(foobar).split(','))
But that's uglier than sin. Why not just reference the values directly?
x_value, y_value = foobar.x, foobar.y
Using the example in Adam's answer:
class Foobar(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '({foo.x}, {foo.y})'.format(foo=self)
Would result in:
foo = Foobar(2, 3)
print(foo)
'(2, 3)'