基于Python中的另一个对象属性创建一个类的对象

创建一个新对象的最佳实践是什么,该对象使用 Python 中另一种类类型的现有对象的属性?

假设我有一个MvsObject的对象MvsClass我想创建一个不同类的新对象,该对象使用属性densePointClouds使用类sparsePointClouds的方法处理它们PointCloud

以下方法是 Python 中的“好习惯”吗?

class PointCloud:    

    def __init__(self, MvsObject):
        self.densePointClouds           = MvsObject.densePointClouds
        self.sparsePointClouds          = MvsObject.sparsePointClouds
德尔甘

你的解决方案很好。您还可以使用@classmethod装饰器来定义两种构建类的方法(以“经典”方式或使用另一个实例)。

class PointCloud:    

    def __init__(self, dense_points_cloud, sparse_points_cloud):
        self.dense_points_cloud = dense_points_cloud
        self.sparse_points_cloud = sparse_points_cloud

    @classmethod
    def from_mvs_object(cls, mvs_object):
        return cls(mvs_object.dense_points_cloud, mvs_object.sparse_points_cloud)

你会像这样实例化它:

point = PointCloud.from_mvs_object(mvs_object)

另请注意,我重命名了属性,因为使用 Python,首选使用蛇形大小写来命名变量。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章