Python 只调用一次 __init__() 方法

发布于 2024-12-12 05:04:38 字数 93 浏览 2 评论 0原文

有没有办法只调用一个类的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

七度光 2024-12-19 05:04:38

如果你想要一个单例,其中一个类只有一个实例,那么你可以创建一个装饰器,如下所示,从 PEP18

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    pass

尝试一下:

>>> a = MyClass()
>>> b = MyClass()
>>> a == b
True

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:

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    pass

Try it out:

>>> a = MyClass()
>>> b = MyClass()
>>> a == b
True
只是我以为 2024-12-19 05:04:38

没有直接的方法来禁用 __init__,但有几种方法可以解决这个问题。其中之一是有一面旗帜:

class Class:
    _init_already = False
    __init__(self):
        if not Class._init_already:
            ...
            Class._init_already = True

但这很丑。你真正想要实现的目标是什么?

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:

class Class:
    _init_already = False
    __init__(self):
        if not Class._init_already:
            ...
            Class._init_already = True

But this is ugly. What is it that you are really trying to accomplish?

红玫瑰 2024-12-19 05:04:38

您不应该在 __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.

烟酒忠诚 2024-12-19 05:04:38

init 方法将始终被调用,但是您可以创建另一个名为 run() 的方法或其他方法,您可以选择在创建对象后调用该方法。

foo = ClassName()
foo.run() # replacement for __init__

foo2 = ClassName()

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.

foo = ClassName()
foo.run() # replacement for __init__

foo2 = ClassName()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文