Python 只调用一次 __init__() 方法
有没有办法只调用一个类的 init() 方法一次。或者当我从类创建对象时如何禁用 init() 的调用?
Is there any way to call the init() method of a class only one time. Or how can I disable calling of init() when I create an object from a class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你想要一个单例,其中一个类只有一个实例,那么你可以创建一个装饰器,如下所示,从 PEP18:
尝试一下:
If you want a singleton, where there is only ever one instance of a class then you can create a decorator like the following as gotten from PEP18:
Try it out:
没有直接的方法来禁用
__init__
,但有几种方法可以解决这个问题。其中之一是有一面旗帜:但这很丑。你真正想要实现的目标是什么?
There's no direct way to disable
__init__
, but there are a few ways to work around this. One of them is having a flag:But this is ugly. What is it that you are really trying to accomplish?
您不应该在 __init__() 中放入只想运行一次的任何内容。每次创建类的实例时,都会运行
__init__()
。如果您想自定义类的创建,您应该考虑创建一个 元类。基本上,这可以让您定义一个仅在首次定义类时运行一次的函数。
You shouldn't put anything in
__init__()
that you only want to run once. Each time you create an instance of a class__init__()
will be run.If you want to customize the creation of your class you should look into creating a metaclass. Basically, this lets you define a function that is only run once when the class is first defined.
init 方法将始终被调用,但是您可以创建另一个名为 run() 的方法或其他方法,您可以选择在创建对象后调用该方法。
The init method will always be called however you could create another method called run() or something, that you call after creating the object, optionally.