Here's the modified version of your ObjectState class. The changes include:
- Removing the
@dataclass decorator because we need more control over attribute assignment (to support change tracking and callbacks).
- Adding a constructor that accepts two 3-tuples for position and rotation, a float for scale, and a callback function.
- Converting those tuples into dictionaries with keys
'x', 'y', 'z'.
- Implementing property setters to detect changes and invoke the callback.
- Adding a method to deep copy from another
ObjectState instance.
from copy import deepcopy
class ObjectState:
def __init__(self, position: tuple[float, float, float], rotation: tuple[float, float, float], scale: float, callback):
if len(position) != 3 or len(rotation) != 3:
raise ValueError("Position and rotation must be tuples of 3 floats.")
self._position = {'x': position[0], 'y': position[1], 'z': position[2]}
self._rotation = {'x': rotation[0], 'y': rotation[1], 'z': rotation[2]}
self._scale = scale
self._callback = callback
@property
def position(self):
return self._position
@position.setter
def position(self, value: dict[str, float]):
if not isinstance(value, dict) or set(value.keys()) != {'x', 'y', 'z'}:
raise ValueError("Position must be a dictionary with keys 'x', 'y', 'z'.")
self._position = value
self._callback()
@property
def rotation(self):
return self._rotation
@rotation.setter
def rotation(self, value: dict[str, float]):
if not isinstance(value, dict) or set(value.keys()) != {'x', 'y', 'z'}:
raise ValueError("Rotation must be a dictionary with keys 'x', 'y', 'z'.")
self._rotation = value
self._callback()
@property
def scale(self):
return self._scale
@scale.setter
def scale(self, value: float):
self._scale = value
self._callback()
def deep_copy_from(self, other: 'ObjectState'):
"""Copy the state from another ObjectState instance deeply."""
self._position = deepcopy(other._position)
self._rotation = deepcopy(other._rotation)
self._scale = other._scale
# Optionally trigger callback after copying
self._callback()
Example Usage:
def on_change():
print("ObjectState changed!")
# Create an initial instance
state1 = ObjectState((1.0, 2.0, 3.0), (0.0, 0.5, 1.0), 1.0, on_change)
# Modify values
state1.scale = 2.0 # triggers callback
state1.position = {'x': 4.0, 'y': 5.0, 'z': 6.0} # triggers callback
# Create another instance and deep copy
state2 = ObjectState((0.0, 0.0, 0.0), (0.0, 0.0, 0.0), 0.0, on_change)
state2.deep_copy_from(state1)
print(state2.position) # {'x': 4.0, 'y': 5.0, 'z': 6.0}
print(state2.scale) # 2.0
This implementation ensures encapsulation, enforces correct input types, and allows deep copying between instances while maintaining callback behavior.