Python中基于NamedTuple构建Gcode命令类型层级的技术问询
Got it, let's solve this problem for you. You want all your Gcode command classes (built with NamedTuple) to be recognized as subclasses of a common Gcode type via issubclass()—here are two straightforward approaches that fit your needs:
Define a base Gcode class, then have each command NamedTuple inherit from both Gcode and NamedTuple. This makes the inheritance relationship explicit and works seamlessly with Python's type checks.
from typing import NamedTuple class Gcode: """Base type for all Gcode command classes""" pass class G1(Gcode, NamedTuple): """Move command with speed in mm/s""" x: float = None y: float = None z: float = None speed: float = None absolute: bool = True # Verify the subclass check print(issubclass(G1, Gcode)) # Output: True
This approach is great if you don't mind updating each command class's inheritance list—it's easy to read and maintain, especially for smaller sets of commands.
If you prefer not to modify the inheritance of your existing NamedTuple command classes, you can use Python's abc module to register them as virtual subclasses of Gcode. This keeps your command classes clean while still enabling issubclass() checks.
from typing import NamedTuple import abc class Gcode(metaclass=abc.ABCMeta): """Base type for all Gcode command classes""" pass class G1(NamedTuple): """Move command with speed in mm/s""" x: float = None y: float = None z: float = None speed: float = None absolute: bool = True # Register G1 as a subclass of Gcode Gcode.register(G1) # Verify the subclass check print(issubclass(G1, Gcode)) # Output: True
To make this even cleaner for multiple commands, create a decorator to handle registration automatically:
def gcode_command(cls): Gcode.register(cls) return cls @gcode_command class G2(NamedTuple): """Arc move command""" x: float = None y: float = None i: float = None j: float = None absolute: bool = True print(issubclass(G2, Gcode)) # Output: True
Which to Choose?
- Use Explicit Inheritance if you want clear, visible type relationships and have a manageable number of command classes.
- Use ABC Registration if you want to keep your existing
NamedTupledefinitions untouched or need dynamic registration of commands.
内容的提问来源于stack exchange,提问作者Nick Parker

