如何在python中使用self

2024-05-19 15:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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())

此代码导致异常:

^{pr2}$

有人能解释一下在调用方法时如何使用“self”吗?在


Tags: selfboxdef编程widthlengthdimensionsheight
3条回答

如果您编写box = Box,则使box成为一个引用类Box的变量。很少需要变量来引用类。调用类的方法时,需要提供该类的实例作为第一个参数,但尚未创建任何此类实例。在

相反,写box = Box()-它将创建类Box的实例。然后剩下的代码就有效了。在类实例上调用类方法时,该实例作为附加的第一个参数传递,即方法定义中名为self的参数。在

使用括号创建类的实例

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

为了增加答案,您可以尝试将self理解为当它被编码时,python会在内部将objects方法转换为从类中调用它,因此当您调用

SomeBoxObject.setDimensions(someLen, otherLen, evenOtherLen)

Python将其转换为

^{pr2}$

相关问题 更多 >