小编gal*_*gos的帖子

如何在 python 中初始化类中列表元素的值

    def __init__(self):
        self.planets = ['Mercury', 'Venus', 'Mars',
                        'Jupiter', 'Saturn','Uranus',
                        'Neptune', 'Pluto']
        self.planets[0] = 0.38
        self.planets[1] = 0.91
        self.planets[2] = 0.38
        self.planets[3] = 2.34
        self.planets[4] = 0.93
        self.planets[5] = 0.92
        self.planets[6] = 1.12
        self.planets[7] = 0.62

    def calculate_spaceweight(self, weight):
        for i in range(len(self.planets)):
            print("your weight on", self.planets[i], " is", weight * self.planets[i] )
if __name__ == '__main__':

    weight = float(input("what is your Earthly weight: "))
    obj1 = Planet()
    print(obj1.calculate_spaceweight(weight))
Run Code Online (Sandbox Code Playgroud)

输出是错误的,我知道有更好的方法来初始化列表中的值,但我不知道如何实现。这是它的输出:

your weight on 0.38  is 57.0
your weight on 0.91  is …
Run Code Online (Sandbox Code Playgroud)

python class list

1
推荐指数
1
解决办法
75
查看次数

标签 统计

class ×1

list ×1

python ×1