Python Forum
function that run once for all objects - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: function that run once for all objects (/thread-35120.html)

Pages: 1 2


RE: function that run once for all objects - Gribouillis - Oct-16-2021

You can simply override the __init__method after the first instance's creation
class Spam:
    def __init__(self):
        Spam.thingy = "eggs"
        _other_init(self)
        Spam.__init__ = _other_init
        print("Hey! I'm the first Spam instance'")

def _other_init(self):
    print("Initializing", self)

for i in range(3):
    Spam()
Output:
ens@thom:~$ python tmp/initruc.py Initializing <__main__.Spam object at 0x7fb34a8b14c0> Hey! I'm the first Spam instance' Initializing <__main__.Spam object at 0x7fb34a8b14c0> Initializing <__main__.Spam object at 0x7fb34a8b14c0>