2015-12-23 107 views
1

我想從一堆變量中讀取組合信息。 我想這在這裏:生成協議字符串

class MyStruct: 
    first_byte = 0 
    second_byte = 0 
    combined = str(hex(first_byte)) + " " + str(hex(second_byte)) 

test = MyStruct() test.first_byte = 36 test.second_byte = 128 

print("MyStruct: test first=%i second=%i comb=%s" %(test.first_byte, test.second_byte, test.combined)) 

我也得到:

> MYSTRUCT:測試第一= 36秒= 128梳=爲0x0爲0x0

但我期待:

> MYSTRUCT:測試第一= 36秒= 128梳= 0X24 0x80的

我看到他們的組合的計算是由只是當它被聲明。但我不知道如何再計算一次。

爲什麼我使用這個: 我想在CARBERRY 這裏創建一個協議,字符串LIN-信號,你可以找到進一步的信息:LIN-command

我想單獨定義每個字節像這樣:

protokol.pid = 10 
protokol.D0 = value_one 
protokol.D1 = value_two 

等..

回答

0

好吧,簡單地說,當你創建CLA行combined = str(hex(first_byte)) + " " + str(hex(second_byte)) 評估SS。 你可以做的是:

class MyStruct: 
    def __init__(self, first_byte, second_byte): 
     self.first_byte = first_byte 
     self.second_byte = second_byte 
     self.combined = hex(first_byte) + " " + hex(second_byte) 


test = MyStruct(36, 128) 
print("MyStruct: test first=%i second=%i comb=%s" %(test.first_byte, test.second_byte, test.combined)) 

我建議你看一看類,方法和屬性,你再往前走之前,你可以拿起了一些有用的工具。

進一步說明: 通過直接在類中聲明first_byte和second_byte,您正在創建靜態類變​​量,可通過MyStruct.first_byteMyStruct.second_byte訪問。下面是一個例子來說明我在說什麼:

>>> class A: 
    tag = 10 
    def set_tag(self, val): 
     self.tag = val 

>>> b = A() 
>>> b.tag 
10 
>>> A.tag 
10 
>>> b.set_tag(5) 
>>> b.tag 
5 
>>> A.tag 
10 
+0

它的工作原理。我想我明白這個代碼中發生了什麼。謝謝。 :) – Markus