Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Classes
#1
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?
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#2
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")
rob101 likes this post
Reply
#3
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
rob101 likes this post
« We can solve any problem by introducing an extra level of indirection »
Reply
#4
(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]
rob101 likes this post
Reply
#5
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.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Understanding Python classes PythonNewbee 3 1,250 Nov-10-2022, 11:07 PM
Last Post: deanhystad
Sad Python classes PythonNewbee 4 1,108 Nov-09-2022, 01:19 PM
Last Post: deanhystad
  Inheritance vs Instantiation for Python classes mr_byte31 7 3,019 Oct-14-2021, 12:58 PM
Last Post: mr_byte31
  Understanding Python super() for classes OmegaRed94 1 1,884 Jun-09-2021, 09:02 AM
Last Post: buran
  Python classes Python_User 15 5,025 Aug-04-2020, 06:57 PM
Last Post: Python_User
  Python Classes leodavinci1990 1 2,123 Nov-27-2019, 07:25 AM
Last Post: buran
  Using classes? Can I just use classes to structure code? muteboy 5 5,156 Nov-01-2017, 04:20 PM
Last Post: metulburr
  use of classes in python Lux 2 3,572 Aug-19-2017, 12:29 PM
Last Post: hbknjr
  python classes prsdll6 14 7,551 Aug-17-2017, 07:26 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020