Search code examples
pythonarraysoopvpython

How to tell class to create a sphere in Python?


I try to transfer my project(solar system) to OOP. I don't know how to tell the class that it should create a sphere for every project? How can I assign it with "shape"?

Original code:

...

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

Solution

  • I make the assumption you defined you Sphere class as follow:

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

    To define the Planet class, you can inherit the Sphere class, like below:

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

    You can use this class like this:

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

    note it’s better to follow the coding style of the PEP8: the class names should be in CamelCase.