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

时间:2018-08-23 17:37:27

标签: 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((mercury,venus,earth,mars,jupiter,saturn,uranus,neptun,pluto))

OOP:

...
planets = []


class Planet(object):
    def __init__(pos,radius,mass,velocity,make_trail)

sun = Planet((0,0,0),5,2e30,(0,0,0)True)
...
planets.extend((mercury,venus,earth,mars,jupiter,saturn,uranus,neptun,pluto))

1 个答案:

答案 0 :(得分:2)

我假设您对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))

note 最好遵循PEP8的编码风格:类名应使用CamelCase。