为什么我在Python中创建一个水瓶类时会得到“dimension is not defined”?

91zkwejq  于 2023-05-27  发布在  Python
关注(0)|答案(1)|浏览(135)

我正在尝试创建一个类来确定水瓶的一些特性:体积,材料,颜色和它的大小(但我希望大小取决于体积,例如如果只有500ml,那么大小是小的,但如果有2000ml,瓶子是大的。我真的迷路了。
我是一个初学者,它我做了这个项目,使我可以学习如何使用类和构造函数,所以任何解释将不胜感激。

class WaterBottle:
    def __init__(self, volume, material, colour, dimmension):
        self.volume = volume
        self.material = material
        self.colour = colour
        self.dimmension = dimmension
    volume = int(input("How many ml fit in your bottle?: "))
    def dimmension(volume):
        if volume <= 500:
            dimmension == "small"
        elif volume < 501 and  evianBottle.volume <= 1000:
            dimmension == "med"
        else:
            dimmension == "large"
material = input("What material is your bottle?: ")
colour = input("What colour is your water bottle?:")
ml = WaterBottle.volume
dimmension = WaterBottle.dimmension(ml)
evianBottle = WaterBottle(WaterBottle.volume, material, colour, dimmension)

print(f"Your bottle is {dimmension} because it hold {ml}, it is made out of {material} and it is {colour}")

我希望用户输入瓶子有多少毫升,瓶子的材料和瓶子的颜色。之后,我想程序,以确定如果瓶是小,中或大。
但不断发生的是,它说,dimmension我们没有定义。

bvn4nwqk

bvn4nwqk1#

您的代码有几个问题,我已更正并作为注解进行了解释
我建议你阅读文档并学习类的教程,这样你就可以熟悉类示例、属性、方法、构造函数等概念。这样你会更好地理解我的评论

class WaterBottle:
    # don't pass dimension to the contructor,
    # it will be calculated from the other attributes
    def __init__(self, volume, material, colour):
        self.volume = volume
        self.material = material
        self.colour = colour
        # calculate the dimension by calling the method get_dimension
        self.dimension = self.get_dimension()

    # here you need self as the first parameter
    # since the method needs to access class attributes. 
    # You don't need to pass volume
    # since you can access it as it is an attribute
    def get_dimension(self):
        # append self keword to attributes
        if self.volume <= 500:
            # assignment operator is only one single equal sign
            self.dimension = "small"
        # you can chain comparison operators for readability
        elif 500 < self.volume <= 1000:
            self.dimension = "med"
        else:
            self.dimension = "large"

# here you request inputs from the user
material = input("What material is your bottle?: ")
colour = input("What colour is your water bottle?:")
volume = int(input("How many ml fit in your bottle?: "))

# instantiate the class
evianBottle = WaterBottle(volume, material, colour)

# get the instance attributes and print them
# split long lines into multiple lines to avoid
# horizontal scrolling
print(f"Your bottle is {evianBottle.dimension} \
        because it hold {evianBottle.volume} ml, \
        it is made out of {evianBottle.material} \
        and it is {evianBottle.colour}")

相关问题