python构造函数调用成员函数_从构造函数调用成员函数

I know this question has a similar title to this: C++: calling member functions within constructor? but I am asking a more general question.

Is it good practice to call member functions from within a constructor? It makes reading the code easier and I prefer the encapsulation type way of doing it (ie. each block of code has a single objective).

An illustrative example, in python:

class TestClass:

def __init__(self):

self.validate()

def validate(self):

# this validates some data stored in the class

Is this a better way of doing it than writing the validate code inside the constructor? Are there drawbacks to this method? For example is it more costly with the function overhead?

I personally prefer it for readability but that's just my preference.

Cheers

解决方案

I don't think there is anything inherently wrong in calling member functions from a constructor provided that they are not virtual functions.

The problem with calling virtual member functions from a constructor is that a subclass can override the function. This will cause the constructor to call the overridden implementation in the subclass, before the constructor for the subclass part of the object has been called.

In Java, any one of the private, static or final access modifiers will make the method safe to call from a constructor by preventing a virtual call to the superclass method. I don't think these techniques are available in Python.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值