i have to swap the two variable using setter and getter but its giving the same exact answer
class Thing:
def __init__(self, thing1=0, thing2=0):
self._thing1 = thing1
self._thing2 = thing2
def get_assignThings(self) :
return self._thing1, self._thing2
def set_assignThings(self, x, y):
self._thing1 = x
x = y
self._thing2 = y
obj = Thing()
obj.set_assignThings(2, 3)
print(obj.get_assignThings())
try this,
def set_assignThings(self, x, y):
self._thing1, self._thing2 = y,x
Change the order how they are returned or set:
ie here : return self._thing2, self._thing1
or self._thing1 = y
self._thing2 = x
Full code:
class Thing:
def __init__(self, thing1=2, thing2=3):
self._thing1 = thing1
self._thing2 = thing2
def get_assignThings(self):
return self._thing2, self._thing1
def set_assignThings(self, x, y):
self._thing1 = x
self._thing2 = y
obj = Thing()
obj.set_assignThings(2, 3)
print(obj.get_assignThings())
Out:
(3, 2)
Related
Suppose I want to create a class called "Point". Suppose I only ever plan on making two points because that's important. I want to create a method that can be called by either instance or "point" that gives the distance between the two points. How would I go about doing that?
This is what my code looks like.
import math
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self): # Just filler code
return math.sqrt((self_2.x - self_1.x)**2+(self_2.y - self_1.y)**2) # Just filler code
point_1 = Point(0,0)
point_2 = Point(3,4)
print(point_1.distance()) # Should return 5.0
print(point_2.distance()) # Should return 5.0
Obviously I know what I made here doesn't work, but I'm just trying to give an idea of what the print statement should do. How would I go about doing this?
import math
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self,other):
return math.sqrt((self.x - other.x)**2+(self.y - other.y)**2)
point_1 = Point(0,0)
point_2 = Point(3,4)
print(point_1.distance(point_2)) # Should return 5.0
print(point_2.distance(point_1)) # Should return 5.0
You should use a second class that specifically represents two points.
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to(self, other):
return abs(complex(self.x, self.y) - complex(other.x, other.y))
class PointPair:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def distance(self):
return self.p1.distnace_to(self.ps2)
point_1 = Point(0,0)
point_2 = Point(3,4)
pair = PointPair(point_1, point_2)
print(pair.distance()
or a regular function
def distance(p1, p2):
return abs(complex(p1.x, p1.y) - complex(p2.x, p2.y))
print(distance(point_1, point_2))
from math import pi
class Circle(object):
'Circle(x,y,r)'
def __init__(self, x=0, y=0, r=1):
self._r = r
self._x = x
self._y = y
def __repr__(self):
return 'Circle({},{},{})'.\
format(self.getx(), self.gety(),\
self.getr())
#silly, but has a point: str can be different from repr
def __str__(self):
return 'hello world'
def __contains__(self, item):
'point in circle'
px, py = item
return (self.getx() - px)**2 + \
(self.gety() - py)**2 < self.getr()**2
def getr(self):
'radius'
return self._r
def getx(self):
'x'
self._lst.append(self._x)
return self._x
def gety(self):
'y'
self._lst.append(self._y)
return self._y
def setr(self,r):
'set r'
self._r = r
def setx(self,x):
'set x'
self._x = x
def sety(self,y):
'set y'
self._y = y
def move(self,x,y):
self._x += x
self._y += y
def concentric(self, d):
d = self._list
def area(self):
'area of circle'
return (self.getr())**2*pi
def circumference(self):
'circumference of circle'
return 2*self.getr()*pi
My question is worded kinda awkwardly but what I am trying to do is check if 2 different circles have the same center (x,y). I think the easiest way to solve this would be to input the 2 points into a list but I am not sure how to compare the 2 lists as every time i try my code it adds everything to the same list
Add the following method to your Circle class.
def equal_center(self, other):
'check if another circle has same center'
return (self._x == other._x) & (self._y == other._y)
Usage
C1 = Circle(3, 5, 8)
C2 = Circle(3, 5, 10)
C3 = Circle(3, 2, 1)
C1.equal_center(C2) # True
C1.equal_center(C3) # False
I would recommend creating a function which takes two circle objects and returns if the coordinates are the same or not by comparing the x and y values of each object:
def same_center(circle_1, circle_2):
if circle_1.getx() == circle_2.getx() and circle_1.gety() == circle_2.gety():
return True
else:
return False
This solution is much easier than using lists and should be easy to implement.
If you have two instances of the class...
a = Circle(0,0,1)
b = Circle(0,0,1)
You could add them to a list of circles...
circles = [a,b]
And loop through the list, checking their values...
for i in circles:
for j in filter(lambda x : x != i, circles):
if i._x == j._x and i._y == j._y:
return True #two circles have same center
This should work for n instances of the class, though if its only two you want to check
if a._x == b._x and a._y == a._y:
return True
I have 2 modules in my project:
1- Ant.py
from threading import Thread
from Ant_farm import Ant_farm
ant_farm = Ant_farm(20, 20)
class Ant(Thread):
def __init__(self, x, y):
global ant_farm
Thread.__init__(self)
self.x = x
self.y = y
ant_farm.matrix[self.x][self.y] = True # At this point the arguments has initialized?
def move(self, x, y):
ant_farm.matrix[self.x][self.y] = False
self.x = x
self.y = y
ant_farm.matrix[self.x][self.y] = True # At this point the value has changed?
def run(self):
while True:
ant_farm.move_ant(self)
t = Ant(0, 0)
print(ant_farm[0][0])
t.move(1, 0)
2- Ant_farm.py
from threading import Condition
def matrix(x, y):
return [[False for j in range(y)] for i in range(x)]
class Ant_farm():
def __init__(self, x, y):
self.c = Condition() # I don't know if I have to put "self" before
self.matrix = matrix(x, y)
def move_ant(self, ant):
new_pos = {0: tuple(x0, y0 - 1),
1: tuple(x0 + 1, y0),
2: tuple(x0, y0 + 1),
3: tuple(x0 - 1, y0)}
x0, y0 = ant.x, ant.y
x1, y1 = new_pos[random.randrange(0, 4)]
with self.c:
try:
while self.matrix[x1][y1]:
self.c.wait()
self.matrix[x0][y0] = False
ant.move(x1, y1)
# It's not end and I have to review
except Exception: # Wich exceptions can appear?
pass
def __str__(self):
pass
In both omit the comments.
When I execute the Ant module, raises this error:
AttributeError: Ant_farm instance has no attribute '__getitem__'
in the line 27 (print(ant_farm[0][0])). Why does this?
As the error message says, you did not define what ant_farm[i] is (the function __getitem__).
You probably want something like this in your Ant_farm class:
def __getitem__(i):
return self.matrix[i]
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']
Here is a class:
class CoordinateRow(object):
def __init__(self):
self.coordinate_row = []
def add(self, input):
self.coordinate_row.append(input)
def weave(self, other):
result = CoordinateRow()
length = len(self.coordinate_row)
for i in range(min(length, len(other))):
result.add(self.coordinate_row[i])
result.add(other.coordinate_row[i])
return result
This is a part of my program:
def verwerk_regel(regel):
cr = CoordinateRow()
coordinaten = regel.split()
for coordinaat in coordinaten:
verwerkt_coordinaat = verwerk_coordinaat(coordinaat)
cr.add(verwerkt_coordinaat)
cr2 = CoordinateRow()
cr12 = cr.weave(cr2)
print cr12
def verwerk_coordinaat(coordinaat):
coordinaat = coordinaat.split(",")
x = coordinaat[0]
y = coordinaat[1]
nieuw_coordinaat = Coordinate(x)
adjusted_x = nieuw_coordinaat.pas_x_aan()
return str(adjusted_x) + ',' + str(y)
But I'm geting an error at "cr12 = cr.weave(cr2)":
for i in range(min(length, len(other))):
TypeError: object of type 'CoordinateRow' has no len()
You need to add a __len__ method, then you can use len(self) and len(other):
class CoordinateRow(object):
def __init__(self):
self.coordinate_row = []
def add(self, input):
self.coordinate_row.append(input)
def __len__(self):
return len(self.coordinate_row)
def weave(self, other):
result = CoordinateRow()
for i in range(min(len(self), len(other))):
result.add(self.coordinate_row[i])
result.add(other.coordinate_row[i])
return result
In [10]: c = CoordinateRow()
In [11]: c.coordinate_row += [1,2,3,4,5]
In [12]: otherc = CoordinateRow()
In [13]: otherc.coordinate_row += [4,5,6,7]
In [14]:c.weave(otherc).coordinate_row
[1, 4, 2, 5, 3, 6, 4, 7]
Iterating over a range of len(something) is very much an anti-pattern in Python. You should be iterating over the contents of the containers themselves.
In your case, you can just zip the lists together and iterate over that:
def weave(self, other):
result = CoordinateRow()
for a, b in zip(self.coordinate_row, other.coordinate_row):
result.add(a)
result.add(b)
return result
Here is the complete solution for the Cart and Item class implementation.
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
def getPrice(self):
return self.price
def getName(self):
return self.name
class ShoppingCart:
def __init__(self):
self.list = []
def __len__(self):
return len(self.list)
def add(self, item):
self.list.append(item)
def total(self):
total = 0
for item in self.list:
total = total + item.getPrice()
return total
other is of type CoordinateRow, which does not have a length. Use len(other.coordinate_row) instead. This is the list that does have the length property.