Tutorial: Building Python Classes#

class Particle:

    def __init__(self, charge=0, position=0):
        """
        Initialize particle with charge and position in 1D
        """
        self.charge=charge
        self.position=position

    def modify_position(self, new_x):
        self.position=new_x 
electron = Particle(charge=-1, position=3.5)
electron.charge
-1
electron.position
3.5
electron.modify_position(23)
print(electron.position)
23
class Atom:
    
    def __init__(self, symbol, atomic_number, atomic_mass):
        """
        Initialize an atom with its chemical symbol, atomic number, and atomic mass.
        """
        self.symbol = symbol
        self.atomic_number = atomic_number
        self.atomic_mass = atomic_mass

    def __repr__(self):
        """
        Representation of the atom.
        """
        return f"{self.symbol} (Atomic Number: {self.atomic_number}, Atomic Mass: {self.atomic_mass} u)"

    def change_isotope(self, new_mass):

        self.atomic_mass = new_mass
hydrogen = Atom("H", 1, 1.008)
oxygen   = Atom("O", 8, 15.999)

Build Molecule Object with useful functions relying on Atom class#

class Molecule:
    
    def __init__(self, name):
        """
        Initialize a molecule with a name and an empty list of atoms.
        """
        self.name = name
        self.atoms = []

    def add_atom(self, atom, count=1):
        """
        Add an atom to the molecule with a specific count.
        """
        
    def molecular_weight(self):
        """
        Calculate the molecular weight of the molecule.
        """
        
        return 

    def formula(self):
        """
        Generate the chemical formula of the molecule.
        """


    def __repr__(self):
        """
        Representation of the molecule.
        """