【发布时间】:2021-08-03 01:27:05
【问题描述】:
我有一个代表 Atom 的类,它有两组坐标,其中一组是笛卡尔坐标,我想遵循最佳架构实践从类中获取该信息。
之前我创建了多个类方法来获取不同类型的属性,但我觉得这不是 Python 的,并且不必要地使我的代码混乱,但是我不确定通常的解决方案是什么。
由于它可能有助于某人回答,请参阅下面的 Atom 类:
class Atom():
def __init__(self, element, x_coord, y_coord, z_coord):
'''
Instantiate new atom object.
'''
#Check information is correct
if not isinstance(element, str):
raise ValueError('Element must be a string.')
if not isinstance(x_coord, int) and not isinstance(x_coord, float):
raise ValueError('All coordinates must be numeric, x is not.')
if not isinstance(y_coord, int) and not isinstance(y_coord, float):
raise ValueError('All coordinates must be numeric, y is not.')
if not isinstance(z_coord, int) and not isinstance(z_coord, float):
raise ValueError('All coordinates must be numeric, z is not.')
self.coordinates = np.array([x_coord, y_coord, z_coord]).astype(float)
self.cartesian = None
self.element = element
def __repr__(self):
'''
Atom representation.
'''
x, y, z = list(self.coordinates)
return f"Atom('{self.element}', {x}, {y}, {z})"
def __copy__(self):
x, y, z = [float(x) for x in list(self.coordinates)]
return Atom(self.element, x, y, z)
def set_cartesian(self, vector_space):
'''
Set the cartesian coordinates of the atom, based on a vector space -
generally that of a unitcell. Requires column vectors.
'''
self.cartesian = vector_space @ self.coordinates.T
我希望使用单一方法来处理所有属性,以保持类整洁。我知道我可以只使用“class.attribute”,但据我了解,如果您想重命名某些内容,这可能会导致代码长期中断。
【问题讨论】:
-
我不明白你的意思。无论你在某处使用什么,如果你重命名它并且不更新引用,就会破坏它。
-
我猜这是编写一个封装属性的方法的想法,无论您重命名属性是什么,它都不会改变。但是,我可能想多了,您通常会使用“class.attribute”来获取属性访问权限吗?
-
如果您需要使用过去某个时候创建的类,但希望属性具有不同的名称,请不要更改现有类,请编写一个适配器并按原样使用原始类。
-
谢谢,这真的很有帮助。所以你会建议一般使用“class.attribute”,然后在必要时使用适配器?
标签: python class architecture attributes