1

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?

3
  • If you define them with self.name they become "global" variables within the class. You could use self.x, self.y = self.origin Commented Jul 28, 2017 at 11:27
  • 2
    @AntonvBR: I would call them instance variables. Global ones are a different thing... Commented Jul 28, 2017 at 11:41
  • @SergeBallesta You are absolutely right, I couldn't find a better name and hence the citation "" marks. Commented Jul 28, 2017 at 12:26

1 Answer 1

1
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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.