简体   繁体   English

你可以在 OOP 类中使用 VPython 吗?

[英]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?我想要做的是使用 VPython 的 sphere 命令来表示行星和恒星,有没有办法在定义新的类时在类中使用它?

Of course.当然。 For example, end your Planet init with this:例如,用以下内容结束您的 Planet init

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.其中 pos 和 radius 是 VPython 球体属性,而质量和速度是您自己的属性。

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:对于 VPython 问题,最好发布到 VPython 论坛,那里有更多的 VPython 用户会看到您的问题,而不是发布到 stackoverflow:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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