I'm trying to make a program to add vectors using __add __:
class vects:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self, vect):
total_x = self.x + vect.x
total_y = self.y + vect.y
return vects(total_x, total_y)
plusv1 = vects.__add__(2,5)
plusv2 = vects.__add__(1,7)
totalplus = plusv1 + plusv2
The error produced is as follows:
line 12, in <module> plusv1 = vects.__add__(2,5)
line 7, in __add__ total_x = self.x + vect.x
AttributeError: 'int' object has no attribute 'x'
You don't use __add__ like that! :-) __add__ will get implicitly invoked when + is used on an instance of the Vects class.
So, what you should first do is initialize two vector instances:
v1 = Vects(2, 5)
v2 = Vects(1, 7)
and then add them:
totalplus = v1 + v2
If you add a nice __str__ to get a nice representation of your new vector:
class Vects:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self, vect):
total_x = self.x + vect.x
total_y = self.y + vect.y
return Vects(total_x, total_y)
def __str__(self):
return "Vector({}, {})".format(self.x, self.y)
You can get a view of totalplus by printing it:
print(totalplus)
Vector(3, 12)
Related
I have to write a code to find the different between two point by passing value via two objects as below.
But I am getting TypeError: init() missing 3 required positional arguments: 'x', 'y', and 'z'
class Point:
def __init__(self, x, y,z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '(point: {},{},{})'.format(self.x, self.y, self.z)
def distance(self, other):
return sqrt( (self.x-other.x)**2 + (self.y-other.y)**2 + (self.z -other.z)**2 )
p = Point()
p1 = Point(12, 3, 4)
p2 = Point(4, 5, 6)
p3 = Point(-2, -1, 4)
print(p.distance(p1,p3))
The problem comes from this line:
p = Point()
When you defined you class, you specified it has to be passed 3 parameters for it to be initialised (def __init__(self, x, y,z)).
If you still want to be able to create this Point object without having to pass those 3 parameters, you can make them optional like this :
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
This way, if you were to not specify these parameters (as you did), it will create a point with coordinates {0, 0, 0} by default.
You are not passing the required 3 arguments for p = Point()
fixed your errors
from math import sqrt
class Point:
def __init__(self, x, y,z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '(point: {},{},{})'.format(self.x, self.y, self.z)
def distance(self, other):
return sqrt( (self.x-other.x)**2 + (self.y-other.y)**2 + (self.z -other.z)**2 )
# p = Point() # not required
p1 = Point(12, 3, 4)
p2 = Point(4, 5, 6)
p3 = Point(-2, -1, 4)
print(p1.distance(p3)) # use this to find distance between p1 and any other point
# or use this
print(Point.distance(p1,p3))
class Point:
def __init__(self, x, y,z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '(point: {},{},{})'.format(self.x, self.y, self.z)
def distance(self, other):
return math.sqrt( (self.x-other.x)**2 + (self.y-other.y)**2 + (self.z -other.z)**2 )
p1 = Point(12, 3, 4)
p2 = Point(4, 5, 6)
p3 = Point(-2, -1, 4)
print(Point.distance(p1,p3))
It works like this.You should not define a P point seperate than the other three points. Every point is a seperate instance. But when you try to use the function just call the class.
How to access multiple instances at same time through a function in a class?
I have learnt about parameters like other, but what if I have 3 objects and I need to access them all in the same function at the same time, how can I do that?
So here is the code I'm trying to correct:
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other, other_1):
return Vector2D(self.x + other.x + other_1.x, self.y + other.y)
first = Vector2D(5, 7)
second = Vector2D(3, 9)
third = Vector2D(1, 1)
result = first + second + third
print(result.x)
print(result.y)}
It's showing the following error:
TypeError: __add__() missing 1 required positional argument: 'other_1'
How can I correct it?
Just remove the other_1 parameter:
>>> class Vector2D:
... def __init__(self, x, y):
... self.x = x
... self.y = y
... def __add__(self, other):
... return Vector2D(self.x + other.x, self.y + other.y)
...
>>> first = Vector2D(5, 7)
>>> second = Vector2D(3, 9)
>>> third = Vector2D(1, 1)
>>> result = first + second + third
>>>
>>> print(result.x)
9
>>> print(result.y)
17
The idea is that first + second + third is equivalent to (first + second) + third. Python only adds two things together at a time.
class type_name:
def __init__(self, *field_names):
self.x = field_names[0]
self.y = field_names[1]
self._fields = [x for x in field_names]
def get_y(self):
return self.y
def __getitem__(self, ind):
fstr = 'self.get_' + str(self._fields[ind]) #this would give me 5 i want self.y so I construct a string such as 'self.get_y()'
#and then return eval on that string to return the value
Using this code above,
Point = pnamedtuple('Point', ['x','y'], mutable = False)
origin = Point(0,5)
print(origin[1])
It should also work with origin['y']
The below piece of code is giving me a error for some reason, Can someone tell me what would be the problem..
Basically, I create 2 classes Point & Circle..THe circle is trying to inherit the Point class.
Code:
class Point():
x = 0.0
y = 0.0
def __init__(self, x, y):
self.x = x
self.y = y
print("Point constructor")
def ToString(self):
return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"
class Circle(Point):
radius = 0.0
def __init__(self, x, y, radius):
super(Point,self).__init__(x,y)
self.radius = radius
print("Circle constructor")
def ToString(self):
return super().ToString() + \
",{RADIUS=" + str(self.radius) + "}"
if __name__=='__main__':
newpoint = Point(10,20)
newcircle = Circle(10,20,0)
Error:
C:\Python27>python Point.py
Point constructor
Traceback (most recent call last):
File "Point.py", line 29, in <module>
newcircle = Circle(10,20,0)
File "Point.py", line 18, in __init__
super().__init__(x,y)
TypeError: super() takes at least 1 argument (0 given)
It looks like you already may have fixed the original error, which was caused by super().__init__(x,y) as the error message indicates, although your fix was slightly incorrect, instead of super(Point, self) from the Circle class you should use super(Circle, self).
Note that there is another place that calls super() incorrectly, inside of Circle's ToString() method:
return super().ToString() + \
",{RADIUS=" + str(self.radius) + "}"
This is valid code on Python 3, but on Python 2 super() requires arguments, rewrite this as the following:
return super(Circle, self).ToString() + \
",{RADIUS=" + str(self.radius) + "}"
I would also recommend getting rid of the line continuation, see the Maximum Line Length section of PEP 8 for the recommended way of fixing this.
super(..) takes only new-style classes. To fix it, extend Point class from object. Like this:
class Point(object):
Also the correct way of using super(..) is like:
super(Circle,self).__init__(x,y)
class Point(object):
x = 0.0
y = 0.0
def __init__(self, x, y):
self.x = x
self.y = y
print("Point constructor")
def ToString(self):
return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"
class Circle(Point,object):
radius = 0.0
def __init__(self, x, y, radius):
super(Circle,self).__init__(x,y)
self.radius = radius
print("Circle constructor")
def ToString(self):
return super(Circle, self).ToString() + \
",{RADIUS=" + str(self.radius) + "}"
if __name__=='__main__':
newpoint = Point(10,20)
newcircle = Circle(10,20,0)
I have the following code embeded in a class.Whenever I run distToPoint it gives the error 'unsupported operand type(s) for -: 'NoneType' and 'float'' I don't know why it's returning with NoneType and how do I get the subtraction to work?
Both self and p are supposed to be pairs.
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def distToPoint(self,p):
self.ax = self.x - p.x
self.ay = self.y - p.y
self.ac = math.sqrt(pow(self.ax,2)+pow(self.ay,2))
For sake of comparison,
import math
class Point(object):
def __init__(self, x, y):
self.x = x + 0.
self.y = y + 0.
def distToPoint(self, p):
dx = self.x - p.x
dy = self.y - p.y
return math.sqrt(dx*dx + dy*dy)
a = Point(0, 0)
b = Point(3, 4)
print a.distToPoint(b)
returns
5.0
You should check what value of p you are sending to the function, so that it has an x and y that are floats.
Old post (on second thought, I don't think you were trying to use distToPoint this way):
distToPoint doesn't return a value, this is probably the problem.