从构造函数调用成员函数 [英] Calling member functions from a constructor

查看:715
本文介绍了从构造函数调用成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题的标题与此类似: C ++:在内部调用成员函数构造函数?,但我要问一个更笼统的问题.

从构造函数内部调用成员函数是一种好习惯吗?它使读取代码更容易,我更喜欢使用封装类型的方式(例如,每个代码块都有一个目标).

一个说明性示例,在python中:

class TestClass:
    def __init__(self):
        self.validate()

    def validate(self):
        # this validates some data stored in the class

这比在构造函数中编写validate代码更好吗?这种方法有缺点吗?例如,函数开销是否更昂贵?

出于可读性考虑,我个人更喜欢它,但这只是我的偏爱.

欢呼

解决方案

我认为从构造函数调用成员函数前提是它们不是虚函数,这并不存在任何内在的错误. /p>

从构造函数调用虚拟成员函数的问题是子类可以覆盖该函数.这将导致构造函数在对象的子类部分的构造函数被调用之前调用子类中的重写实现.

在Java中, private static final 访问修饰符中的任何一个都可以防止构造函数从方法构造函数中调用该方法对超类方法的虚拟调用.我认为这些技术在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.

这篇关于从构造函数调用成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆