首页 > 解决方案 > 什么是添加负乘法作为关键字参数的 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那里输入,因为这看起来不直观。

我希望我的问题是有道理的。感谢您提供的任何指导。

标签: pythonpython-3.xidiomskeyword-argument

解决方案


怎么样

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)))

推荐阅读