struct in python code example
Example 1: python struct pack
import struct
var = struct.pack('hhl', 5, 10, 15)
print(var)
print(struct.unpack('hhl', var))
Example 2: python c like struct
from typing import NamedTuple
class User(NamedTuple):
name: str
class MyStruct(NamedTuple):
foo: str
bar: int
baz: list
qux: User
my_item = MyStruct('foo', 0, ['baz'], User('peter'))
print(my_item)
Example 3: python c like struct
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
z: float = 0.0
p = Point(1.5, 2.5)
print(p)