Reputation: 11
I'm new to programming and I'm confused as to how you call a method/parameter that is defined within a class in Python 2. For example (with obstacle being a previous class made),
class Block(Obstacle):
def __init__(self, origin, end, detection=9.):
self.type = 'block'
self.origin = origin
self.end = end
x1 = self.origin[0]
y1 = self.origin[1]
x2 = self.end[0]
y2 = self.end[1]
def __str__(self):
return "block obstacle"
When I generate an environment, I define different x1, y1, x2 and y2 values (essentially signifying the coordinate points of the corners of the block). I have another later method where I needs the values of x1, y1, x2 and y2 in calculating something, but I'm confused as to how I actually call them into this new function? What parameters would I put in this new function?
Upvotes: 1
Views: 2943
Reputation: 3049
import math
I would make x1
--> self.x1
so you can have it as an object variable.
Inside the class object you can define these functions for calculation as an example.
def calculate_centre(self):
self.centre_x = self.x2 - self.x1
self.centre_y = self.y2 - self.y1
self.centre = (centre_x, centre_y)
def distance_between_block_centres(self, other):
block_x, block_y = other.centre
distance = math.sqrt((self.centre_x - block_x)**2 + (self.centre_y - block_y)**2)
return distance
block = Block(stuff)
block_2 = Block(other_stuff)
if you want to call these function using the objects youve created:
block.calculate_centre()
block_2.calculate_centre()
distance_between = block.distance_between_block_centres(block_2)
And even external to your object call the variables:
print block.centre
#>>> (3, 5)
Lastly you can run the calculations of the centre without having to call it every time you create your object if your put it in def __init__()
:
self.calculate_centre()
Upvotes: 1