【发布时间】:2020-11-17 04:49:52
【问题描述】:
我创建了一个简单的类来接收一个表示数组形状的元组,并将名称分配给最后三个维度(深度、高度、宽度)作为类属性。我有兴趣将这些属性设置为属性,以便对实例形状的任何更改都会反映在这些属性中。这会造成我有重复代码的情况,如果我决定将来分配更多维度名称或设置器/删除器,情况会变得更糟。
这是我的(精简)课程:
class Shape():
"""A class to represent 4-dimension names of a shape tuple"""
def __init__(self, shape):
"""Shape instance is initialized with a shape tuple
Args:
shape (tuple): a tuple representing an array shape
"""
self.shape = shape
@property
def shape(self):
return self._shape
@shape.setter
def shape(self, value):
self._shape = value
# ndim is needed in case number of elements in shape is not equal to 3
@property
def ndim(self):
return len(self.shape)
# width, height, depth are similar
@property
def width(self):
"""Last dimension of shape"""
if self.ndim >= 1:
return self.shape[-1]
@property
def height(self):
"""Second last dimension of shape"""
if self.ndim >= 2:
return self.shape[-2]
@property
def depth(self):
"""Third last dimension of shape"""
if self.ndim >= 3:
return self.shape[-3]
实例化类:
x = (4, 5)
shape1 = Shape(x)
print(shape1.shape)
print((shape1.depth, shape1.height, shape1.width))
(4, 5)
(无、4、5)
将形状属性设置为新值:
shape1.shape = (3, 2, 1)
print(shape1.shape)
print((shape1.depth, shape1.height, shape1.width))
(3, 2, 1)
(3, 2, 1)
所以我的课程按预期工作,但是有没有一种更简洁的方法可以在循环中设置多个类似的属性?我试图在 init 的循环中使用 setattr()。这适用于设置常规类属性,但我找不到使用它设置属性的方法,这意味着属性将不再反映对实例形状的更新。
【问题讨论】:
标签: python properties attributes python-decorators