【发布时间】:2011-03-06 17:32:36
【问题描述】:
我知道这个问题的标题与此类似:C++: calling member functions within constructor?,但我问的是一个更笼统的问题。
从构造函数中调用成员函数是一种好习惯吗?它使阅读代码更容易,我更喜欢封装类型的方式(即每个代码块都有一个目标)。
一个说明性的例子,在 python 中:
class TestClass:
def __init__(self):
self.validate()
def validate(self):
# this validates some data stored in the class
这是否比在构造函数中编写validate 代码更好?这种方法有缺点吗?例如,函数开销是否更昂贵?
我个人更喜欢它的可读性,但这只是我的偏好。
干杯
【问题讨论】: