如何在python中使用self

时间:2015-06-06 01:41:29

标签: python

我是编程新手,我希望有人使用“自我”来解释。在以下上下文中的python中。

class Box:
    def __init__(self):
        self.length = 1.0
        self.width = 1.0
        self.height = 1.0    

    def set_dimensions(self, newL, newW, newH):
        self.length = newL
        self.width = newW
        self.height = newH          

    def volume(self):
        return (self.length * self.width * self.height)

box = Box:
box.set_dimensions(2.0,3.0,4.0)
print(box.volume())

此代码导致异常:

Error: box.set_dimensions(2.0,3.0,4.0) needs exactly 4 arguments, 3 given

有人可以解释如何使用' self'在调用方法时请?

3 个答案:

答案 0 :(得分:1)

使用括号创建班级的实例

box = Box()                       # Use parenthesis here not :
box.set_dimensions(2.0,3.0,4.0)   # Now no error
print(box.volume())               # Prints 24.0

答案 1 :(得分:1)

如果您撰写box = Box,则会box提及引用课程Box的变量。你需要一个变量来引用一个类是非常罕见的。调用类的方法时,需要提供该类的实例作为第一个参数,但是您还没有创建任何此类实例。

而是编写box = Box() - 这将创建类Box的实例。然后代码的其余部分将是有效的。在类实例上调用类方法时,实例将作为附加的第一个参数传递,即在方法定义中名为self的参数。

答案 2 :(得分:0)

要在答案中添加一些内容,您可以尝试将类函数变量中的self理解为当它被封装时python内部将对象方法转换为从类中调用它,因此当您调用<时/ p>

SomeBoxObject.setDimensions(someLen, otherLen, evenOtherLen)

Python将其变为

Box.setDimensions(SomeBoxObject, someLen, otherLen, evenOtherLen)