可以防止调用init吗

可以防止调用init吗

本文介绍了可以防止调用init吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编辑原始问题,因为我们都专注于您应该这样做.我的问题很简单,我可以这样做吗?怎么办(要知道可能有几种解决方案).因此,我将离开实际的问题并删去背景.

I'm editing the original question because we're all focusing on SHOULD you ever want to do this. My question is simply CAN I do this and HOW (understanding that there may be several solutions). So I'm just going to leave the actual question and cut out the background.

假设我有一个基类和一个子类.我可以在基类中做些什么来防止在子类上调用__init__?或者至少抛出一个异常,甚至在子类上存在__init__时也要记录日志?我确实希望在父类上调用__init__方法.

Suppose I have a base class and a child class. Is there anything I can do in the base class to prevent __init__ from being called on the child class - or at least throw an exception or even log if __init__ exists or is called on the child class? I do want the __init__ method to be called on the parent class.

编辑/结论-探索了答案中给出的选项后,我认为这样做是不好的风格.我将以另一种方式解决我的问题.尽管如此,希望下面的答案对您有所帮助.

Edit/Conclusion - After exploring the options presented in the answers, I decided that doing this would be bad style. I will solve my problem a different way. Nonetheless, hopefully the answers below are helpful in case someone else wants to do this.

推荐答案

这是完全可行的,但我认为您不应该这样做.告诉用户如何使用您的课程,他们应该服从.另外,如果有人在继承子类,他应该知道如何调用父类的初始化方法.

That's quite doable, but I don't think you should.Tell the users how to use your class and they should obey. Also, if someone is subclassing he should know how to call the parent's initialization method.

作为概念证明,这是如何使用元类(Python 2.x语法)来完成的:

As a proof of concept, here's how it can be done with metaclasses (Python 2.x syntax):

>>> class WhoMovedMyInit(object):
        class __metaclass__(type):
            def __init__(self, *args, **kw):
                super(type,self).__init__(*args, **kw)
                if self.__init__ is not WhoMovedMyInit.__init__:
                    raise Exception('Dude, I told not to override my __init__')


>>> class IAmOk(WhoMovedMyInit):
        pass

>>> class Lol(WhoMovedMyInit):
        def __init__(self):
            pass

Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    class Lol(WhoMovedMyInit):
  File "<pyshell#31>", line 6, in __init__
    raise Exception('Dude, I told not to override my __init__')
Exception: Dude, I told not to override my __init__

您还可以将子类方法替换为警告用户或在运行时"上引发错误的方法.

You can also replace the subclass __init__ method to one which warns the user or raises an error on "runtime".

这篇关于可以防止调用init吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 17:15