【发布时间】:2020-12-03 17:33:11
【问题描述】:
我正在尝试制作一个简单的程序,其中每个实例都必须在循环中进行一些操作:
#this is in a class
class Sphere(Simulation):
spheres = []
def __init__(self, name, mass, ray, position):
self.name = name
self.mass = mass
self.ray = ray
self.position = position
self.behaviour()
def gravity(self):
global G
G = 0.0000000000667408
gravity_force = G * self.mass / self.ray / self.ray
return gravity_force
def behaviour(self):
for sphere in Sphere.spheres:
distance_x = np.sqrt(np.square(self.position[0] - sphere.position[0])) #need to call a planet
distance_y = np.sqrt(np.square(self.position[1] - sphere.position[1]))
distance_z = np.sqrt(np.square(self.position[2] - sphere.position[2]))
distance = (distance_x, distance_y, distance_z)
print("distance from " + self.name + str(distance))
earth = Sphere("earth", 5972000000000000000000000, 6371000, (2, 0, 0))
moon = Sphere("moon", 73420000000000000000000, 1737100, (-2, 0, 0))
mars = Sphere("mars", 639000000000000000000000, 3389500, (1, 3, 2))
earth.gravity()
moon.gravity()
mars.gravity()
问题是:我希望每个行星都必须测量彼此之间的距离。因此,例如对于地球,它将测量与月球和火星的距离。我不知道如何循环执行。距离应该是 (x, y, z) 值的元组。
提前致谢!
【问题讨论】:
标签: python list loops class instance