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.
Related
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)
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
I have to use a class. I have to make sure that x and y are properties.
If the values provided are not convertible to an integer, raise an AttributeError. If we give a value less than 0 to x or y, it is assigned the value 0.
If we give a value greater than 10 to x or y, it is assigned the value 10.
Here is my code:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def getx(self):
x=int()
return self._x
def gety(self):
y=int()
return self._y
if x>=0:
return 0
else if x<=10:
return 10
I want to obtain this:
p = Point(1,12)
print(p.x, p.y) # output "1 10"
p.x = 25
p.y = -5
print(p.x, p.y) # output "10 0"
What are you looking for is clamp() function, which takes 3 arguments: value, desired minimal value and desired maximal value.
Properties are defined by the #property decorator. For testing if the value assigned to property is number I use numbers module. Here is sample code:
import numbers
def clamp(v, _min, _max):
return max(min(v, _max), _min)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
#property
def x(self):
return self.__x
#x.setter
def x(self, value):
if not isinstance(value, numbers.Number):
raise AttributeError()
self.__x = clamp(int(value), 0, 10)
#property
def y(self):
return self.__y
#y.setter
def y(self, value):
if not isinstance(value, numbers.Number):
raise AttributeError()
self.__y = clamp(int(value), 0, 10)
p = Point(1,12)
print(p.x, p.y) # output "1 10"
p.x = 25
p.y = -5
print(p.x, p.y) # output "10 0"
I'm trying to define a class that has an instance of itself as a class variable so I can reference a common instance of it all over the place.
How can I get something like this to work?
class Point():
ORIGIN = Point()
def __init__(self, x=0, y=0):
self.x = x
self.y = y
p0 = Point.ORIGIN
p1 = Point(3,4)
distance = (p1.x*p1.x + p1.y*p1.y) ** .5
print(distance)
You can add the class attribute after the class has been created:
class Point():
def __init__(self, x=0, y=0):
self.x = x
self.y = y
Point.ORIGIN = Point()
You can probably also make it work so that the origin is created lazily via descriptors, or you can probably do something funky using a metaclass -- but that seems unlikely to be worth your while.
You could use a meta class:
>>> class SingletonMeta(type):
... def __init__(cls, name, bases, dct):
... cls.ORIGIN = cls()
...
>>> class Point(metaclass=SingletonMeta):
... def __init__(self, x=0, y=0):
... self.x = x
... self.y = y
...
>>> p0 = Point.ORIGIN
>>> p1 = Point(3,4)
>>> p0
<__main__.Point object at 0x110b7e7b8>
>>> p0.x, p0.y
(0, 0)
Simply create class variables that represent the values you want instead of encapsulating those values in an instance:
class Point:
x = 0
y = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
x,y = Point.x, Point.y
p1 = Point(3,4)
distance = ((p1.x-x)**2 + (p1.y-y)**2) ** .5
print(distance) # prints 5.0
Or, better yet:
class Point:
x = 0
y = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distance(self, other=None):
if other is None:
x,y = Point.x, Point.y
else:
x,y = other.x, other.y
return ((self.x-x)**2 + (self.y-y)**2) ** .5
And then you can do this:
>>> p1 = Point(3,4)
>>> p1.distance()
5.0
>>> p1.distance(Point(3,5))
1.0
Python refactoring
Both the add and sub are very similar. How does one re-factor code like this? The logic is basically inverse of each other.
class point(object):
def __init__( self, x, y ):
self.x, self.y = x, y
def add( self, p ):
x = self.x + p.x
y = self.y + p.y
return point( x, y )
def sub( self, p ):
x = self.x - p.x
y = self.y - p.y
return point( x, y )
First, standard practice is to capitalize classes (so Point, not point). I'd make use of the __add__ and __sub__ (and possibly __iadd__ and __isub__) methods, as well. A first cut might look like this:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x, self.y - p.y)
I know you're looking to pull the logic out into a single method, something like:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def _adjust(self, x, y):
return Point(self.x + x, self.y + y)
def __add__(self, p):
return self._adjust(p.x, p.y)
def __sub__(self, p):
return self._adjust(-p.x, -p.y)
... but that seems more complicated, without much gain.
What about that:
import operator
class point(object):
def __init__( self, x, y ):
self.x, self.y = x, y
def _do_op(self, op, p):
x = op(self.x, p.x)
y = op(self.y, p.y)
return point(x, y)
def add( self, p ):
return self._do_op(operator.add, p)
def sub( self, p ):
return self._do_op(operator.sub, p)
Here's something you could do.
def __add__(self, p): # used this so that you can add using the + operator
x = self.x + p.x
y = self.y + p.y
return point(x, y)
def __sub__(self, p):
return self + point(-p.x, -p.y)