Python Forum
Python Classes - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python Classes (/thread-41554.html)



Python Classes - rob101 - Feb-05-2024

Although I've been coding with Python for a number of years now, I've never constructed a Class before. This is my first attempt.

class Resister:
    def __init__(self, band1, band2, band3):
        bands = {
            "black": 0,
            "brown": 1,
            "red": 2,
            "orange": 3,
            "yellow": 4,
            "green": 5,
            "blue": 6,
            "violet": 7,
            "gray": 8,
            "white": 9,
        }
        multi = {
            "black": 1,
            "brown": 10,
            "red": 100,
            "orange": 1000,
            "yellow": 10 * 1000,
            "green": 100 * 1000,
            "blue": 1000000,
            "violet": 10 * 1000000,
        }
        base_value = (bands[band1] * 10) + bands[band2]
        self.value = base_value * multi[band3]


r1 = Resister("blue", "gray", "red")
print(r1.value)
The 'subject' here is not the point (I know that there's a Python library for this kind of thing), rather is this the way to go, or is there a better way to do this?


RE: Python Classes - paul18fr - Feb-05-2024

Two possibilities (not necessary the best ones)

class Resister:
    
    # variables (dictionaries) outside the constructor
    bands = {
        "black": 0,
        "brown": 1,
        "red": 2,
        "orange": 3,
        "yellow": 4,
        "green": 5,
        "blue": 6,
        "violet": 7,
        "gray": 8,
        "white": 9,
    }    
    
    multi = {
        "black": 1,
        "brown": 10,
        "red": 100,
        "orange": 1000,
        "yellow": 10 * 1000,
        "green": 100 * 1000,
        "blue": 1000000,
        "violet": 10 * 1000000,
    }    
    
    def __init__(self, band1, band2, band3):
        self.Band1 = band1
        self.Band2 = band2
        self.Band3 = band3

    # method to calculate the value        
    def CalculateValue(self):
        return  ((self.bands[self.Band1] * 10) + self.bands[self.Band2]) * self.multi[self.Band3]
    
    
# NewObject = Resister("blue", "gray", "red")
# Value = NewObject.CalculateValue()
Value = Resister("blue", "gray", "red").CalculateValue()
print(f"R1 = {Value} ohms")




class Resister2:
    
    @staticmethod
    def CalculateValue(band1, band2, band3):
        bands = {
            "black": 0,
            "brown": 1,
            "red": 2,
            "orange": 3,
            "yellow": 4,
            "green": 5,
            "blue": 6,
            "violet": 7,
            "gray": 8,
            "white": 9,
        }    
        
        multi = {
            "black": 1,
            "brown": 10,
            "red": 100,
            "orange": 1000,
            "yellow": 10 * 1000,
            "green": 100 * 1000,
            "blue": 1000000,
            "violet": 10 * 1000000,
        }
        return  ((bands[band1] * 10) + bands[band2]) * multi[band3]
    
Value2 = Resister2.CalculateValue("blue", "gray", "red")
print(f"R1 = {Value2} ohms")



RE: Python Classes - Gribouillis - Feb-05-2024

I suggest using Enum for colors and storing the bands as a tuple.
from enum import Enum, auto
from functools import cached_property

class Color(Enum):
    BLACK = 0
    BROWN = auto()
    RED = auto()
    ORANGE = auto()
    YELLOW = auto()
    GREEN = auto()
    BLUE = auto()
    VIOLET = auto()
    GRAY = auto()
    WHITE = auto()

    @cached_property
    def multiplier(self):
        if self.value > Color.VIOLET.value:
            raise ValueError("Invalid Color for resistor multiplier", self)
        return 10**self.value


vars().update(Color.__members__)


class Resistor:
    def __init__(self, band0, band1, band2):
        self.band = tuple((band0, band1, band2))

    def __repr__(self):
        return f"Resistor{self.band!r}"

    @property
    def value(self):
        return self.band[2].multiplier * (10 * self.band[0].value + self.band[1].value)


r = Resistor(BLUE, GRAY, RED)
print(r, r.value, r.band[1])
Output:
λ python paillasse/pf/resistor.py Resistor(<Color.BLUE: 6>, <Color.GRAY: 8>, <Color.RED: 2>) 6800 Color.GRAY



RE: Python Classes - snippsat - Feb-05-2024

(Feb-05-2024, 03:27 PM)rob101 Wrote: The 'subject' here is not the point (I know that there's a Python library for this kind of thing), rather is this the way to go, or is there a better way to do this?
No is this not the best example of class usage as it dos one thing that a function could fine have done,and may by better in this case.
So can make example that fit better for a class,so here is there two method that can be calculated.
Also added docstring and some type hint,this will help when try to use method as will show documation in a Editor or using class from Repl.
class Resistor:
    """A class to represent a resistor and calculate its resistance based on color bands."""
    # Class variables for band color codes,as they may be none changing fixed values
    bands = {
        "black": 0,
        "brown": 1,
        "red": 2,
        "orange": 3,
        "yellow": 4,
        "green": 5,
        "blue": 6,
        "violet": 7,
        "gray": 8,
        "white": 9,
    }
    multipliers = {
        "black": 1,
        "brown": 10,
        "red": 100,
        "orange": 1000,
        "yellow": 10 * 1000,
        "green": 100 * 1000,
        "blue": 1000000,
        "violet": 10 * 1000000,
    }

    def __init__(self, band1, band2, band3):
        """Initialize the resistor with three color bands."""
        self.band1 = band1
        self.band2 = band2
        self.band3 = band3
        self.value = self.resistance()

    def resistance(self) -> float:
        """Calculate and return the resistance value based on the current color bands."""
        try:
            base_value = (
                self.bands[self.band1] * 10
            ) + self.bands[self.band2]
            return base_value * self.multipliers[self.band3]
        except KeyError as e:
            raise ValueError(
                f"Invalid color '{e.args[0]}' for a band."
            ) from None

    def power_dissipation(self, voltage: float) -> float:
        """Calculate and return the power dissipation based on a given voltage."""
        try:
            power = (voltage**2) / self.value
            return power
        except ZeroDivisionError:
            return "Resistance value must be greater than 0 to calculate power dissipation."

# Example usage
r1 = Resistor("blue", "gray", "red")
print(f'{r1.resistance()} Omhs')
# Calculate power dissipation for a 5V voltage
power_dissipation = r1.power_dissipation(5)
print(f"Power Dissipation: {power_dissipation} Watts")
Output:
6800 Omhs Power Dissipation: 0.003676470588235294 Watts
To show a image on how documation get better in a editor eg VS Code when take mouse over a method.
[Image: y6kvoJ.png]


RE: Python Classes - rob101 - Feb-05-2024

Thank you all for the rapid and very helpful responses.

I will study what has been said here and apply what I can learn from this.