Python program not working..The main part keep showing error - python

class point:
def __init__(self,z,d):
self.x = z
self.y = d
def display(self,z,d):
self.x = self.z
self.y = self.d
def setX(self, z):
self.x = z
def setY(self, d):
self.y = d
def getX(self):
return self.x
def getY(self):
return self.y
def show(self):
print(self.x)
print(self.y)
p1 = point() //error
print("Point P1:")
p1.show()
print("Updated value:")
p1.display(5, 6)
p1.setX(9)
p1.setY(4)
p1.show()
print("Point P2:")
p2=point()
p2.setX(9)
p2.setY(4)
p2.show()
print("Updated value:")
p2.display(6, 3)
p2.show()
My program keep showing me error that z and d are missing in the object section,,i donno how to correct it i keep trying but more n more errors keeps showing up.
Traceback (most recent call last):
File "P:\xxxyyy.py", line 29, in <module>
p1 = point() //error
TypeError: __init__() missing 2 required positional arguments: 'z' and 'd'

Don't forget to pass in z and d in the constructor, eg:
p1 = point(1,2)
Also, in the display function, you try to set self.x to self.z and self.y to self.d. self.z and self.d don't exist (self means it should be a class attribute, which it isn't), you should instead use the function's input parameters:
self.x = z
self.y = d

class point:
def __init__(self,z,d):
self.x = z
self.y = d
def display(self,z,d):
self.x = z #not self.z
self.y = d #not self.d
def setX(self, z):
self.x = z
def setY(self, d):
self.y = d
def getX(self):
return self.x
def getY(self):
return self.y
def show(self):
print(self.x)
print(self.y)
First fix this, you are updating with display using two new variables that its taking in, so we just cast those variables not self.z / self.d
p1 = point(1,2)
print("Point P1:")
p1.show()
Create your instance with values that it needs __ini__(self, z, d) needs a z and d value
print("Updated value:")
p1.display(5, 6)
p1.setX(9)
p1.setY(4)
p1.show()
If p1.display is updating the values to 5,6 then why update them again with setX/setY pretty much you are making z=5, d=6 then z=9 d=4
And then you just repeat these small errors for p2

Related

TypeError: Vector() takes no arguments

I am trying to Implement the set_x, set_y, init, and str methods in the class Vector above, the output of this test should be:
#Vector: x=4, y=4
#Vector: x=5, y=5
#Vector: x=3, y=7
#Vector: x=3, y=7
.
class Vector:
def __init__(self, x, y): self.x = x self.y = y
def set_x(self,x): set_x = x
def set_y(self,y): set_y = y
def __str__(self): return ("Vector: x=%s, y=%s", set_x, set_y)
#__init__ and __str__ v1=Vector(4,4) print(v1)
#Important Remark
#v1.x,v1.y =4,4 # should return an error since x and y are private
# test set_x and set_y v1.set_x(5) v1.set_y(5) print(v1)
v1.set_x(1) v1.set_y(9) print(v1)
# test __init__ again print(Vector(1,9))
I believe this is what you are trying to do:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def set_x(self, x):
self.x = x
def set_y(self, y):
self.y = y
def __str__(self):
return f"Vector: x={self.x}, y={self.y}"
v1 = Vector(1, 9)
print(v1)

Where does the value of the variable in the subclass go?

class A(object):
def __init__(self, x):
self.x = x
def f(self, x):
return 2*x
def g(self, x):
return self.f(x)
class B(A):
def g(self, y):
return 3*y + self.x
class C1(B):
def __init__(self, x, y):
B.__init__(self,x)
self.y = y
def f(self, x):
return self.x + self.y
class C2(B):
def __init__(self, x, y):
B.__init__(self,x)
self.y = y
def f(self, x):
return x + self.x + self.y
a = A(5)
b = B(2)
c1 = C1(3,5)
c2 = C2(3,5)
When I do "What does the expression c2.f(4) evaluate to?", I was not sure where self.x in the f function in class C2 points to.
Could you give me some suggestions?
c2.f(4) makes 12. The value of x in function f is 4 because that is the argument in c2.f(4). The value of c2's self.x is 3 because C2 inherits from B, which inherits from A, where the line self.x = x occurs. In this line, x is what is entered in the line c2 = C2(3,5) and because it is assigned to self.x, c2's self.x is 3. Because of the line self.y = y in class C2, the instance c2's y value is what is entered in the line c2 = C2(3,5), 5. 4 + 3 + 5 makes 12.

Python giving me two different results while performing the same operation on the same objects twice

I created a class vector2D in python with a method to add vectors. Then I used it to add the same vectors twice and got different results. Why did that happen?
Here's the code:
class vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
self.x += other.x
self.y += other.y
return self.x, self.y
#Creating vector objects
v1 = vector2D(2, 3)
v2 = vector2D(4, 8)
#using the redefined addition operator to add vector objects
v = v1 + v2 #output: (6, 11)
print(v)
#Adding again
v = v1 + v2 #output: (10, 19)
print(v)
You both add the vectors in place and return the result!
def __add__(self, other):
self.x += other.x
self.y += other.y
return self.x, self.y
This changes first vector's parameters! += means self.x = self.x + other.x.
Do this instead:
def __add__(self, other):
result_x = self.x + other.x
result_y = self.y + other.y
return result_x, result_y
Your doing in place assignment, when you do this
self.x += other.x
you are changing the x attribute of the object it self, so when you do the second addition the x is changed.
One more thing __add__ should return an instance of the same class, Developer when using your class they will expect when they add vector2d to another vector2d they get a vector2d but you are returning a tuple:
class vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return self.__class__(self.x + other.x, self.y + other.y)
So when you add vector2D + vector2D you get vector2D instance.

Function missing 1 required positional argument [duplicate]

This question already has an answer here:
Missing 1 required positional argument
(1 answer)
Closed last year.
I'm getting this error :
Traceback (most recent call last):
File "C:/Users/mali03/Desktop/Python/Practice/p2.py", line 18, in <module>
first.subtraction(1, 2)
TypeError: subtraction() missing 1 required positional argument: 'y'
Here is my calculator class
class calculator:
def __init__(self, x, y):
self.x = x
self.y = y
def addition(self, x, y):
return self.x + self.y
def subtraction(self, x, y):
if self.x > self.y:
return self.y - self.x
else:
return self.x - self.y
I then call subtraction with the following:
first = calculator
first.subtraction(1, 2)
Like stated previously, you don't have to include parameters in your addition or subtraction functions if you already gather that information in the __init__ function.
Like so:
class calculator:
def __init__(self, x, y):
self.x = x
self.y = y
def addition(self):
return self.x + self.y
def subtraction(self):
if self.x > self.y:
return self.y - self.x
else:
return self.x - self.y
first = calculator
print(first(5,10).addition())
Alternatively, if you do want to have x and y parameters in your addition and subtraction functions, you can adjust your code like so:
class calculator:
def addition(self, x, y):
return x + y
def subtraction(self, x, y):
if x > y:
return y - x
else:
return x - y
first = calculator
print(first().addition(5, 10))
Where parameters of individual functions are used instead to the parameters given to the class object.
Either ways work, it depends on how you want to use the class.
Alternatively you could do:
class calculator():
def addition(self, x, y):
return x + y
def subtraction(self, x, y):
if x > y:
return y - x
else:
return x - y
first = calculator()
print(first.subtraction(1, 2))
Also not entirely sure if x > y: was your intention or if you really wanted if x < y:
You don't need to specify x and y in subtraction or addition:
class calculator:
def __init__(self, x, y):
self.x = x
self.y = y
def addition(self):
return self.x + self.y
def subtraction(self):
if self.x > self.y:
return self.y - self.x
else:
return self.x - self.y
self will cover retrieving x and y for you, since you are referencing those instance variables. Otherwise, you will need to specify them on call:
# Yields 2-1 rather than 4-3
result = calculator(1,2).subtraction(3,4)
You do, however, need to specify them when instantiating your class
myinst = calculator(1,2)
first = calculator makes first refer to the class. But first = calculator(1, 2) makes first an object of the class calculator. This initializes self for all other functions called on first. This also sets the values for self.x and self.y because __init__ is called as soon as object is created. Hence, when first = calculator(x, y) is used, self has a value along with self.x and self.y, and when parentheses are not used, they do not have a value. That gives a missing argument error.
Next, as others have already referred, once __init__ is called, x and y are initialized for the object. And so, you don't need them while declaring other functions. self.x and self.y can directly be used there which will now refer to 1 and 2 respectively in this case.
Hope it helps.

How to use property()

I'm having trouble on how to implement property to protect attributes.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def set_x(self, x):
if '_x' in dir(self):
raise NotImplementedError("Cannot change x coordinate")
else:
self._x = x
def get_x(self):
return self._x
#I beleive my mistake is here. I'm not sure if I'm implementing this correctly
x = property(get_x, set_x, None, None)
So I want to prevent any user from changing the x-coordinate. My question is, how do I get python to redirect the user to the set_x() and get_x() methods? I've tried running this code in terminal and whenever I apply the following, the point changes.
p = point(3, 4)
p.x = 5 #x is now 5
You only need this much:
class Point:
def __init__(self, x, y):
self._x = x
self.y = y
def get_x(self):
return self._x
x = property(get_x)
You can set the hidden field self._x in your init, then you don't need a setter for x at all. And have get_x return self._x rather than self.x so it doesn't try and call itself.
You can use the #property decorator to do this even more succinctly.
class Point:
def __init__(self, x, y):
self._x = x
self.y = y
#property
def x(self):
return self._x
The following code works on both python2.x and python3.x:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def set_x(self, x):
if '_x' in dir(self):
raise NotImplementedError("Cannot change x coordinate")
else:
self._x = x
def get_x(self):
return self._x
x = property(get_x, set_x, None, None)
p = Point(2, 3)
print(p.x) # 2
p.x = 6 # NotImplementedError
Pretty much all I did was inherit from object (to get it to work on python2.x) and use the name Point rather than point (which would have been a NameError before).
There are other things you can do to clean it up a bit (e.g. khelwood's suggestion of just writing the getter -- or DSM's suggestion of using hasattr instead of '_x' in dir(self)).
Note, if you really just want a type that takes an x and y arguments that you want to be immutable -- Maybe you should consider using a colledctions.namedtuple
from collections import namedtuple
Point = namedtuple('Point', 'x,y')
p = Point(2, 3)
p.x # 2
p.y # 3
p.x = 6 # AttributeError: can't set attribute

Categories

Resources