aboutsummaryrefslogtreecommitdiff
path: root/jarrio/week10resistors.py
blob: f7041c713045325a461fb81258707b00a4205a74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class resistor:
    def __init__(self, resistance: float):
        self._resistance = resistance;
        self.has_current(0)

    def has_current(self, current: float):
        self._current = current
        self._voltage = current*self._resistance

    def has_voltage(self, voltage: float):
        self._voltage = voltage
        self._current = voltage/self._resistance

    def __repr__(self):
        return f"Resistor with resistance {self._resistance}: current {self._current} through voltage {self._voltage}"

class parallel(resistor):
    def __init__(self, r1: resistor, r2: resistor):
        self._r1 = r1
        self._r2 = r2
        self._resistance = 1/(1/r1._resistance + 1/r2._resistance)

    def _update_children(self):
        self._r1.has_voltage(self._voltage)
        self._r2.has_voltage(self._voltage)

    def has_current(self, current: float):
        self._current = current
        self._voltage = current*self._resistance
        self._update_children()

    def has_voltage(self, voltage: float):
        self._voltage = voltage
        self._current = voltage/self._resistance
        self._update_children()

class series(resistor):
    def __init__(self, r1: resistor, r2: resistor):
        self._r1 = r1
        self._r2 = r2
        self._resistance = r1._resistance + r2._resistance

    def _update_children(self):
        self._r1.has_current(self._current)
        self._r2.has_current(self._current)

    def has_current(self, current: float):
        self._current = current
        self._voltage = current*self._resistance
        self._update_children()

    def has_voltage(self, voltage: float):
        self._voltage = voltage
        self._current = voltage/self._resistance
        self._update_children()

r24 = resistor(24)
r4 = resistor(4)
r12 = resistor(12)
r5 = resistor(5)
rtot = parallel( r24, series( parallel(r4,r12), r5 ) )
rtot.has_current(1)
print(r24)
print(r5)
print(r4)
print(r12)