【问题标题】:Python method call from class to class从类到类的 Python 方法调用
【发布时间】:2013-04-06 17:30:51
【问题描述】:

我正在学习 Python,但我对从一个类到另一个类的调用语法感到困惑。我做了很多搜索,但无法回答任何工作。我总是得到如下变化:

TypeError: __init__() takes exactly 3 arguments (1 given)

帮助非常感谢

import random
class Position(object):
    '''
    Initializes a position
    '''
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def getX(self):
        return self.x

    def getY(self):
        return self.y

class RectangularRoom(object):
    '''
    Limits for valid positions
    '''
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def getRandomPosition(self):
        '''
        Return a random position
        inside the limits
        '''        
        rX = random.randrange(0, self.width)
        rY = random.randrange(0, self.height)

        pos = Position(self, rX, rY)
        # how do I instantiate Position with rX, rY?

room = RectangularRoom()
room.getRandomPosition()

【问题讨论】:

    标签: python class call


    【解决方案1】:

    您不需要传递self - 这是新创建的实例,由 Python 自动提供。

    pos = Position(rX, rY)
    

    请注意,这里的错误发生在这一行,但是:

    room = RectangularRoom()
    

    这一行的问题是您没有提供widthheight

    【讨论】:

    • 谢谢,帮了大忙。仍在努力理解课程!
    【解决方案2】:

    也许这些前面问题的答案可以帮助你理解为什么 python 决定在方法上添加显式的特殊第一个参数:

    错误信息可能有点神秘,但一旦你看到它一两次,你就知道要检查什么了:

    1. 您是否忘记在方法上定义 self/cls 第一个参数?
    2. 您是否传递了所有必需的方法参数? (第一个不算)

    那些期望/给定的数字很有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      相关资源
      最近更新 更多