2

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))
Ragnarök
  • 138
  • 10
  • 1
    You appear to be simply replacing whatever class `sphere` is with a new class `Planet`. – chepner Aug 23 '18 at 17:43
  • Derive `class Planet` from `class sphere`. i.e. `class Planet(sphere)`. Be sure to use `super()` to initialize `sphere` base class in `Planet`'s `__init__()` method. – martineau Aug 23 '18 at 17:45
  • @martineau can you help me with the super() how to put it in my code I don't really get it where... – Ragnarök Aug 23 '18 at 17:50
  • @ColinM. those coding details are in any tutorial on Python class inheritance. Please consult with the available on-line resources before posting here. – Prune Aug 23 '18 at 18:01
  • 1
    If you're using Python 3.x, inside `Planet`'s `def __init__(pos,radius,mass,velocity,make_trail):` method definition it would look something like `super().__init__(pos=pos, radius=radius, make_trail=make_trail)`. You'll need to manually save or otherwise deal with the other arguments the method receives (probably following) that call. For example, `self.mass = mass`. – martineau Aug 23 '18 at 18:03

1 Answers1

2

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.

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103