如何实现 .transpose() 是 .IT(就像在 numpy 中一样)

How to implement a .tranpose() as .T (like in numpy)

假设我有以下 class 包含一个 Numpy 数组 a.

class MyClass():
    def __init__(self,a,b):
        self.a = a
        self.other_attributes = b
    def transpose(self):
        return MyClass(self.a.T,self.other_attributes)

由于这个"transpose the data, keep the rest unchanged"方法会经常使用,我想实现一个像Numpy的.T一样的短命名属性。我的问题是如果不在初始化时调用 .transpose 我不知道该怎么做,我。即,我只想在需要时进行转置,而不是将其保存在另一个属性中。这可能吗?

使用property计算属性。这也可以用于缓存计算结果以备后用。

class MyClass():
    def __init__(self, a, b):
        self.a = a
        self.other_attributes = b

    @property
    def T(self):
        try:
            return self._cached_T  # attempt to read cached attribute
        except AttributeError:
            self._cached_T = self._transpose()  # compute and cache
            return self._cached_T

    def _transpose(self):
        return MyClass(self.a.T, self.other_attributes)

从Python 3.8开始,标准库提供functools.cached_property自动缓存计算属性。

from functools import cached_property

class MyClass():
    def __init__(self, a, b):
        self.a = a
        self.other_attributes = b

    @cached_property
    def T(self):
        return self._transpose()

    def _transpose(self):
        return MyClass(self.a.T, self.other_attributes)

转置只是数据的视图,因此 "computing" 实例化时的转置实际上不需要任何成本。

In [11]: a = np.random.rand(2, 1)

In [12]: a
Out[12]: 
array([[0.22316214],
      [0.69797139]])

In [13]: b = a.T

In [14]: a[0] = 1

In [15]: b
Out[15]: array([[1.        , 0.69797139]])