Re: Konstanten in Struct-Form in Python

Marc 'BlackJack' Rintsch <[email protected]>
Newsgroups gmane.comp.python.general.german
Organization Aioe.org NNTP Server
Message-ID <[email protected]>
On Mon, 22 Feb 2021 07:00:47 +0100, Michael S. wrote:

> Ich habs jetzt so gemacht. Da muss ich in der Anwendung nur die
> CAN-Signals_Klasse instanzieren, dafür halt in der Lib jeweils jedes
> eigene Signal. Aber die Lib wird eh automatisch generiert.
> 
> class C_frequency:
> 	def __init__(self):
> 		self.ID = "10FC80FC"
> 		self.BitOffset = 48 self.BitLength = 8 self.Gain = 1 
self.ValueOffset
> 		= 0 self.Unit = "Hz"
> 		self.Rate = 0.5
> 
> class C_OutputVoltage:
> 	def __init__(self):
> 		self.ID = "25FF1250"
> 		self.BitOffset = 32 self.BitLength = 16 self.Gain = 0.1
> 		self.ValueOffset = 0 self.Unit = "V"
> 		self.Rate = 0.25
> 
> class C_Cable_temp:
> 	def __init__(self):
> 		self.ID = "12FA5AFC"
> 		self.BitOffset = 0 self.BitLength = 8 self.Gain = 1 
self.ValueOffset =
> 		-40 self.Unit = "°C"
> 		self.Rate = 10
> 		
> class CAN_Signals:
> 	def __init__(self):
> 		self.frequency = C_frequency() self.OutputVoltage = 
C_OutputVoltage()
> 		self.Cable_temp = C_Cable_temp()

Verschiedene Klassen mit genau den gleichen Attributen sieht ”falsch” aus.  Da
würde man eher *eine* Klasse schreiben, die die Attribute hat, und davon dann
mehrere Exemplare erstellen.

Mit `collections.namedtuple()` und Namen die sich an PEP8 halten, könnte das
dann so aussehen:

from collections import namedtuple

Signal = namedtuple(
    "Signal", "id bit_offset bit_length gain value_offset unit rate"
)

FREQUENCY = Signal("10FC80FC", 48, 8, 1, 0, "Hz", 0.5)
OUTPUT_VOLTAGE = Signal("25FF1250", 32, 16, 0.1, 0, "V", 0.25)
CABLE_TEMPERATURE = Signal("12FA5AFC", 0, 8, 1, -40, "°C", 10)

Ciao,
	Marc 'BlackJack' Rintsch
-- 
“I don't care WHO you
 are but your not walking
 on the water while I'm fishing”
_______________________________________________
python-de maillist  -  [email protected]
https://mail.python.org/mailman/listinfo/python-de
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.