如何从类的__init__方法调用变量(Python)?

时间:2017-07-27 13:59:18

标签: python python-2.7 methods parameters

我是编程的新手,我对如何调用Python 2中的类中定义的方法/参数感到困惑。例如(障碍是前一个类),

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"

当我生成一个环境时,我定义了不同的x1,y1,x2和y2值(基本上表示块角的坐标点)。我有另一个后来的方法,我需要在计算某些东西时使用x1,y1,x2和y2的值,但是我对如何将它们实际调用到这个新函数中感到困惑?我将在这个新功能中添加哪些参数?

1 个答案:

答案 0 :(得分:1)

import math

我会x1 - > self.x1所以你可以将它作为一个对象变量。

在类对象中,您可以将这些函数定义为计算示例。

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)

如果您想使用您创建的对象调用这些函数:

block.calculate_centre()
block_2.calculate_centre()
distance_between = block.distance_between_block_centres(block_2)

甚至在你的对象外部调用变量:

print block.centre
#>>> (3, 5)

最后,您可以运行中心的计算,而无需在每次创建对象时调用它,如果您将其放入def __init__()

self.calculate_centre()