Design an immutable type TriAngle representing triangles and implement the
时间: 2024-03-19 18:45:58 浏览: 13
Here is an implementation of the immutable TriAngle class in Python:
```python
from typing import Tuple
import math
class TriAngle:
def __init__(self, a: float, b: float, c: float):
self._sides = (a, b, c)
@property
def sides(self) -> Tuple[float, float, float]:
return self._sides
@property
def angles(self) -> Tuple[float, float, float]:
a, b, c = self._sides
A = math.degrees(math.acos((b**2 + c**2 - a**2) / (2 * b * c)))
B = math.degrees(math.acos((c**2 + a**2 - b**2) / (2 * c * a)))
C = 180 - A - B
return (A, B, C)
def __eq__(self, other: 'TriAngle') -> bool:
return sorted(self.sides) == sorted(other.sides) and sorted(self.angles) == sorted(other.angles)
def __str__(self) -> str:
return f"A triangle with sides {self.sides} and angles {self.angles}"
```
In this implementation, the `TriAngle` class takes three parameters in its constructor, which represent the lengths of the three sides of the triangle. The class has two properties: `sides` and `angles`, which return tuples of the triangle's side lengths and angles respectively. The `angles` property uses the law of cosines to calculate the three angles of the triangle. The class also implements the `__eq__` method to compare two triangles for equality, and the `__str__` method to return a string representation of the triangle.
Since the class has no mutators, it is immutable and can be safely used in multithreaded programs.