如何告诉类在Python中创建球体?

如何告诉类在Python中创建球体?,python,arrays,oop,vpython,Python,Arrays,Oop,Vpython,我尝试将我的项目(太阳系)转移到OOP。我不知道如何告诉类它应该为每个项目创建一个球体?如何将其指定为“形状” 原始代码: ... planets = [] #Sonne sun = sphere(pos = vec(0,0,0), radius = 5, make_trail = True ) sun.mass = 2e30 sun.velocity = vec(0,0,0) ... planets.extend((mercu

我尝试将我的项目(太阳系)转移到OOP。我不知道如何告诉类它应该为每个项目创建一个球体?如何将其指定为“形状”

原始代码:

...

    planets = []

    #Sonne
    sun = sphere(pos = vec(0,0,0), radius = 5, make_trail = True ) 
    sun.mass = 2e30   
    sun.velocity = vec(0,0,0)
    ...
    planets.extend((mercury,venus,earth,mars,jupiter,saturn,uranus,neptun,pluto))
面向对象:


我假设您定义了
Sphere
类,如下所示:

class Sphere(object):
    def __init__(self, pos, radius, make_trail):
        self.pos = pos
        self.radius = radius
        self.make_trail = make_trail
要定义
Planet
类,可以继承
Sphere
类,如下所示:

class Planet(Sphere):
    def __init__(self, pos, radius, make_trail, mass, velocity):
        super().__init__(pos, radius, make_trail)
        self.mass = mass
        self.velocity = velocity
您可以这样使用此类:

# Erde
earth = Planet(
    pos=Vec(0, 0, 0),
    radius=5 * 6371 / 695508,
    make_trail=True,
    mass=5.972e24,
    velocity=Vec(0, 0, 0))

请注意,最好遵循PEP8的编码风格:类名应为CamelCase。

您似乎只是简单地用新的类
Planet
替换任何类
sphere
。从
类sphere
派生
类Planet
。i、 e.
类行星(球体)
。请务必使用
super()
Planet
方法中初始化
sphere
基类。@martineau你能帮我把super()放在我的代码中吗?我真的不知道它在哪里…@ColinM。关于Python类继承的任何教程中都有这些编码细节。在这里发布之前,请咨询可用的在线资源。如果您使用的是Python 3.x,在
Planet
def\uu init\uuuuuuuuuuuu(pos,radius,mass,velocity,make\u trail):
方法定义,它看起来像
super()。\uu init\uuuuuuuuuu(pos=pos,radius=radius,make\u trail=make\u trail)
。您需要手动保存或以其他方式处理该方法接收(可能在调用之后)的其他参数。例如,
self.mass=mass
# Erde
earth = Planet(
    pos=Vec(0, 0, 0),
    radius=5 * 6371 / 695508,
    make_trail=True,
    mass=5.972e24,
    velocity=Vec(0, 0, 0))