python:如何组织类中的方法
python 219
原文标题 :python: How to organize methods in a class
我有这样的情况,我实例化一个有很长计算来计算几个属性的类。下面是一个例子。
class Father():
def __init__(self, fathername, age):
self.fathername = fathername
self.age = age
self.initials = self.initials()
self.initials2 = self.initials2()
self.salary = self.salary(self.age)
# using internal methods
def initials(self):
'''
long calculation
'''
return self.fathername[0:1]
def initials2(self):
'''
long calculation based on initials1 and on many previously calculated attributes
'''
return self.initials.upper()
@staticmethod
def salary(age):
'''
long calculation
'''
result = age*1000
return result
问题是接下来要走的路是什么。a)根本没有方法,所有代码在一起,计算属性时只需设置它们
# peseudocode:
self.attribute = XX
# further calculations
self.attribute2 = YY
b) 如上面的示例代码。使用内部方法来分离功能。包括返回传递给相应属性的值的类方法。优点是可以很好地排列 init 中的所有属性,从而提供一个很好的概览
c) 使用静态方法。我认为这不是要走的路,因为他们永远不会从课堂外被召唤
d) 使用@property。我认为这不是要走的路,因为这意味着每次调用属性时都会重新运行方法。
我会选择选项 b,但不知何故我觉得不是很 Pythonic。
假设方法中的代码很长,还有哪种其他方式可以对该类进行编码?
谢谢