简体   繁体   中英

Can you use VPython in an OOP class?

I'm making a simulation of the solar system, and am using object oriented programming to make it easier to add new planets.

from vpython import *

#gravitational constant
G = 6.674e-11
#seconds in a day
dt = 86400

step = 1
maxstep = 3000

class Planet:

    def __init__(self, mass, radius, position, velocity):
        self.mass = mass
        self.radius = radius
        self.position = position
        self.velocity = velocity

class Star:

    def __init__(self, mass, radius):
        self.mass = mass
        self.radius = radius

Earth = Planet(5.972e24, 6371, vector(0,1.47e8,0), vector(-29.951,0,0))
Mercury = Planet(3.285e23, 2439.7, vector(0,4.6e7,0), vector(-47.400,0,0))
Sun = Star(1.989e30, 696340)

#acceleration vectors
a_Earth = -G*Sun.mass*Earth.position/mag(Earth.position)**3
a_Mercury = -G*Sun.mass*Mercury.position/mag(Mercury.position)**3

#position vectors
Earth.position = Earth.position + Earth.velocity*dt + 0.5*a_Earth*dt**2

What I'm trying to do is to use VPython's sphere command to represent the planets and star, is there a way to use it in the class when defining new ones?

Of course. For example, end your Planet init with this:

return sphere(mass=mass, radius=radius, pos=position, velocity=velocity)

where pos and radius are VPython sphere attributes, whereas mass and velocity are your own attributes.

For VPython questions it's better to post to the VPython forum, where there are many more VPython users who will see your question than if you post to stackoverflow:

https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users

尝试子类化 sphere (is-a) 或让你的类有一个 (has-a) sphere。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM