【问题标题】:How to call variables from the __init__ method of classes (Python)?如何从类(Python)的 __init__ 方法中调用变量?
【发布时间】:2018-01-03 07:34:26
【问题描述】:

我是编程新手,我对如何调用 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 的值​​,但是我对如何将它们实际调用到这个新函数中感到困惑?我会在这个新函数中添加什么参数?

【问题讨论】:

  • 如果您使用 self.name 定义它们,它们将成为类中的“全局”变量。你可以使用 self.x, self.y = self.origin
  • @AntonvBR:我会称它们为 instance 变量。全球的是另一回事......
  • @SergeBallesta 你说得对,我找不到更好的名字,因此引用“”标记。

标签: python python-2.7 methods parameters


【解决方案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()

【讨论】:

    猜你喜欢
    • 2014-03-20
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 2013-12-19
    • 2011-11-06
    • 2017-12-13
    • 2013-10-12
    • 1970-01-01
    相关资源
    最近更新 更多