0

我在 main() 上收到一个属性错误。有人可以帮我吗?这是我的课:

导入数学

Cylinder2() 类:

    def __init__(self, cylRadius = 1, cylHeight = 1):
        self.__radius = cylRadius
        self.__height = cylHeight
    def getPerimeter(self):
        return (2 * math.pi * self.__radius)
    def getEndArea(self):
        return (math.pi * (self.__radius ** 2))
    def getSideArea(self):
        return (2 * (math.pi * (self.__radius * (self.__height))))
    def getSurfaceArea(self):
        return (2 * (math.pi * (self.__radius) * (self.__height + self.__radius)))
    def getVolume(self):
        return (math.pi * (self.__radius ** 2) * self.__height)
    def setRadius(self, r):
        self.__radius = r
    def setHeight(self, h):
        self.__height = h
    def getRadius(self):
        return self.__radius
    def getHeight(self):
        return self.__height

这是主要的():

从 CylinderModule2 导入 *

定义主():

    bottle = Cylinder2(4, 8)

    bottle.setRadius(2)   
    bottle.setHeight(4)
    print("The radius and height of the bottle are: ", bottle.__radius, " and ", bottle.__height)
    print("The perimeter of the bottle end circle is", ("%.2f" % bottle.getPerimeter()))
    print("The end circle area of the bottle is ", ("%.2f" % bottle.getEndArea()))
    print("The side area of the bottle is ", ("%.2f" % bottle.getSideArea()))
    print("The total surface of the bottle is ", ("%.2f" % bottle.getSurfaceArea()))
    print("The volume of the bottle is ", ("%.2f" % bottle.getVolume()))

主要的()

这是我得到的错误: print("瓶子的半径和高度是:", bottle._ radius, " and " , bottle._height ) AttributeError: 'Cylinder2' object has no attribute '__radius'

4

1 回答 1

1

bottle.__radius并且bottle.__height可以粗略地描述为私有变量(即使它们不是真的,你可以在这里阅读我的意思:http: //docs.python.org/2/tutorial/classes.html#private-variables-and -class-local-references ) “私有”变量不能从类外部直接访问。在 Python 中,它们使用两个下划线表示(如 __radius 中)。

所以你想要做的是使用 getter,它们是bottle.getRadius()and bottle.getHeight()

于 2013-10-18T23:53:49.057 回答