python - 什么是添加负乘法作为关键字参数的 Pythonic 方法
问题描述
在某些情况下,我正在将一些几何变换编码到 python 类中,添加一些矩阵乘法方法。3D“场景”内可以有许多 3D 对象。为了允许用户在对整个场景或场景中的一个对象应用变换之间进行切换,我正在计算对象边界框(长方体?)的几何中心,以允许该几何中心充当“ origin”在对象欧几里得空间中,然后仅将变换矩阵乘法应用于该对象。
我的具体问题发生在将点从场景空间映射到局部对象空间时,我从这些点中减去几何中心。然后在转换之后,为了转换回来,我将几何中心添加到点上。有没有一种pythonic方法可以通过关键字参数将我的函数从加法更改为减法?
我不喜欢我现在拥有的东西,它似乎不是很pythonic。
def apply_centroid_transform(point, centroid, reverse=False):
reverse_mult = 1
if reverse:
reverse_mult = -1
new_point = [
point[0] - (reverse_mult * centroid["x"]),
point[1] - (reverse_mult * centroid["y"]),
point[2] - (reverse_mult * centroid["z"]),
]
return new_point
我不想让关键字参数成为multiply_factor=1
然后让用户知道在-1
那里输入,因为这看起来不直观。
我希望我的问题是有道理的。感谢您提供的任何指导。
解决方案
怎么样
def apply_centroid_transform(point, centroid, reverse=False):
if reverse:
centroid["x"]= centroid["x"]*-1
centroid["y"]= centroid["y"]*-1
centroid["z"]= centroid["z"]*-1
new_point = [
point[0] - (centroid["x"]),
point[1] - (centroid["y"]),
point[2] - (centroid["z"]),
]
return new_point
假设 dict 质心中还有其他组件。一般来说,我建议创建一个数据类“质心”和一个数据类“点”,其中 x、y、z 作为属性,以使代码更具可读性。
这看起来像这样:
from dataclasses import dataclass
@dataclass
class Centroid(dataclass):
x: float
y: float
z: float
def reverse(self):
return Centroid(x=self.x*-1, x=self.y*-1, x=self.z*-1)
@dataclass
class Point(dataclass):
x: float
y: float
z: float
def apply_centroid_transform(point: Point, centroid: Centroid, reverse: Bool=False):
if reverse:
centroid = centroid.reverse()
return Point(point.x - (centroid.x), point.y - (centroid.y), point.z - (centroid.z)))
推荐阅读
- amazon-web-services - 如何使用气流将数据从 redshift 导出到 s3?
- nginx - 如何在磁盘上查找与正则表达式匹配的文件?(例如 /123-foo 提供 /123-bar.html)
- android - 尝试在模拟器上安装第二个颤振应用程序时出错
- c++ - understand the pointer pointer in c++ to get the function call
- html - 如何在 GitHub README.md 中显示 Codecov.io 徽章?
- ios - 在导航栏下隐藏 UITableView
- javascript - 如何在数组中记录所有异步函数的结果
- javascript - 如何在标签 Highcharts 中设置“Y”位置
- entity-framework - Linq 选择特定列具有价值的位置
- python - SymPy `solve` 无法求解矩阵方程 A*x = b 当符号被替换为具有 `subs` 的值时