Search code examples
python-3.xnumpypython-class

Perform operations on values with class attributes


Let's say I've made a simple class

class mercury:

    class orbial_characteristics:
        apehilion = 69816900
        perihilion = 46001200
        semi_major_axis = 57909050
        eccentricity = 0.205630
        orbital_period = 87.9691*86400
        orbital_speed = 47.362*1e3

Now, the values given here are in SI units, the value of apehilion for example, is in km. I want to make another class that can convert the value to a given unit, let's say astronomical unit. One method is to pass the value of apehilion directly to that class

change_to_AU(value_of_apehilion)

Which is relatively easy to do. However, what I'm looking for is in the lines of python core operations. Something like this

merc_apehilion_km = mercury.orbital_characteristics.apehilion
merc_apehilion_au = merc_apehilion_km.change_to_AU()

I have recently started working on classes, by reading answers here and web tutorials but I do not get how such an operation can be performed. I even try reading the core files from numpy and pandas as these two libraries that I use most have a number of things that use this notation.


Solution

  • Edit:

    A little research led me to this stack overflow page. Take a look at the libraries mentioned in it, make sure they are actively maintained, and consider using them over doing what I demonstrate below

    End of Edit

    Creating custom methods like this would involve you creating a custom Object for your SI unit values. Here is an example:

    class SIUnit:
        def __init__(self, value):
            self.value = value
    
        def __str__(self):
            return self.value
    
        def to_astronimical_units(self):
            Calculations which convert apehilion to AU go here
    
            return result
    
    class mercury:
    
        class orbial_characteristics:
            apehilion = SIUnit(69816900)
            perihilion = SIUnit(46001200)
            semi_major_axis = SIUnit(57909050)
            eccentricity = SIUnit(0.205630)
            orbital_period = SIUnit(87.9691*86400)
            orbital_speed = SIUnit(47.362*1e3)
    
    

    Keep in mind that the to_astronomical_units method would exist for all SI units you use, not just distance so you may want to create a base SIUnit class then have a subclass for each SI Unit, e.g:

    class SIUnit:
        def __init__(self, value):
            self.value = value
    
        def __str__(self):
            return self.value
    
    class Kilometer(SIUnit):
        def to_au(self):
            Calculations which convert apehilion to AU go here
            return result
    
    class Ampere(SIUnit):
        def to_volts(self, wattage):
            return self.value / wattage