要创建一个非常、非常基本的电路仿真器,可以接受以下组件:
一种固定的、不改变电压的直流电池电源--零resistance
我想“描述”这样的设置:

我想“组件”应该是这样的:
class Battery:
def __init__(self, voltage=None):
self.voltage = voltage
class Resistor:
def __init__(self, resistance=None):
self.resistance = resistance
class Wire:
# how to describe variable connections?
>>> V = Battery(9)
>>> R1, R2, R3 = Resistor(10e3), Resistor(2e3), Resistor(1e3)然后,一旦我有了这些组件,有什么例子来描述它们是如何‘连接’的呢?
发布于 2020-01-28 21:08:48
您可以添加start和end参数,这些参数指示电路中组件的位置。
class BaseComponent:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return f'<{self.__class__.__name__} start={self.start} end={self.end} at 0x{id(self):x}>'
def __eq__(self, other):
if not type(self)==type(other):
return False
return all(v==getattr(other, k) for k, v in self.__dict__.items())
class Battery(BaseComponent):
def __init__(self, start, end, voltage=None):
super().__init__(start, end)
self.voltage = voltage
class Resistor(BaseComponent):
def __init__(self, start, end, resistance=None):
super().__init__(start, end)
self.resistance = resistance
class Wire(BaseComponent):
def __init__(self, start, end):
super().__init__(start, end)然后,您可以通过以下方式进行布局:
V = Battery(8, 1, voltage=9)
w1, w2, w3 = Wire(1, 2), Wire(2, 3), Wire(3, 4)
R1, R2, R3 = Resistor(2, 7, 10e3), Resistor(3, 6, 2e3), Resistor(4, 5, 1e3)
w5, w6, w7 = Wire(5, 6), Wire(6, 7), Wire(7, 8)如果你想得到花哨,你也可以把它变成一个图形。
class Circuit:
"""A directed graph structure for building circuits"""
def __init__(self):
"""Creates the graph. Note only one edge is allowed between nodes"""
self._outward = {}
self._inward = {}
@staticmethod
def _norm(name):
return str(name)
def add_node(self, name):
"""
Adds a single node to the graph. The `name` is converted to a string.
"""
node = self._norm(name)
# check for existance
if node in self._outward:
return node
self._outward.setdefault(node, {})
self._inward.setdefault(node, {})
return node
def add_component(self, component):
"""
Adds a circuitry component to the circuit.
"""
s = self._norm(component.start)
e = self._norm(component.end)
if self.has_edge(s, e):
raise KeyError(f'A link from {s} to {e} already exists')
start = self.add_node(component.start)
end = self.add_node(component.end)
self._outward[start][end] = component
self._inward[end][start] = component
def has_node(self, node):
return self._norm(node) in self._outward
def has_component(self, component):
start = self._norm(component.start)
end = self._norm(component.end)
return component==self._outward.get(start, {}).get(end)
def has_edge(self, start, end):
s = self._norm(start)
e = self._norm(end)
return bool(e in self._outward.get(s, {}))
def __iadd__(self, other):
self.add_component(other)
return self从这里你可以通过以下方式建立电路:
circuit = Circuit()
for c in (V, w1, w2, w3, R1, R2, R3, w5, w6, w7):
circuit.add_component(c)https://stackoverflow.com/questions/59956935
复制相似问题