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

How to tell class to create a sphere in Python?

我尝试将我的项目(太阳系)转移到 OOP。我不知道如何告诉 class 它应该为每个项目创建一个球体?如何用 "shape" 分配它?

原代码:

...

    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))

糟糕:

...
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))

我假设你定义你 Sphere class 如下:

class Sphere(object):
    def __init__(self, pos, radius, make_trail):
        self.pos = pos
        self.radius = radius
        self.make_trail = make_trail

定义Planetclass,可以继承Sphereclass,如下:

class Planet(Sphere):
    def __init__(self, pos, radius, make_trail, mass, velocity):
        super().__init__(pos, radius, make_trail)
        self.mass = mass
        self.velocity = velocity

您可以这样使用 class:

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

注意 最好遵循 PEP8 的编码风格:class 名称应采用 CamelCase。