You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现3D点对象属性(x/y/z)的自动获取与设置

问题描述

我尝试用Python创建一个3D点对象,编写了如下代码:

import numpy as np

class Point3D:
    def __init__(self, x, y, z):

        self.vector = np.matrix([x, y, z])
        self.vector.reshape(3, 1)

    def x(self): return self.vector.item((0, 0))
    def y(self): return self.vector.item((0, 1))
    def z(self): return self.vector.item((0, 2))

我使用numpy创建列矩阵,最终将其用于渲染引擎开发。希望无需输入self.vector.item((0, 0))这类复杂语句,直接通过point.x自动获取向量中的x值,同时支持point.x = 5这样的赋值操作。请问是否有可行的实现方式?

我曾尝试在__init__中初始化这些属性,但每次都需手动更新;之后编写了方法来简化获取操作,但仍无法实现设置功能。

解决方案

可以使用Python的@property装饰器实现需求,它能将方法伪装成属性,既支持直接取值,也能通过赋值语法修改底层numpy矩阵的数据。

修改后的代码如下:

import numpy as np

class Point3D:
    def __init__(self, x, y, z):
        # 直接初始化为3x1列矩阵,reshape不修改原矩阵,需赋值生效
        self.vector = np.matrix([x, y, z]).reshape(3, 1)
    
    @property
    def x(self):
        return self.vector.item((0, 0))
    
    @x.setter
    def x(self, value):
        self.vector.itemset((0, 0), value)
    
    @property
    def y(self):
        return self.vector.item((1, 0))
    
    @y.setter
    def y(self, value):
        self.vector.itemset((1, 0), value)
    
    @property
    def z(self):
        return self.vector.item((2, 0))
    
    @z.setter
    def z(self, value):
        self.vector.itemset((2, 0), value)

关键说明:

  • @property装饰器把x()、y()、z()方法转为只读属性,直接通过point.x即可取值,无需加括号。
  • 配套的@x.setter等装饰器定义了赋值逻辑,执行point.x = 5时会自动调用对应方法修改矩阵元素。
  • 原代码中self.vector.reshape(3,1)不会修改原矩阵,需在__init__中直接赋值生成列矩阵。

使用示例:

p = Point3D(1, 2, 3)
print(p.x)  # 输出1
p.x = 5
print(p.x)  # 输出5
print(p.vector)  # 输出[[5],[2],[3]]

内容的提问来源于stack exchange,提问作者Math Magician

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 03:52:20