Python Forum
function that run once for all objects
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
function that run once for all objects
#2
Why not set a class attribute in the __init__? New objects can check if it exists and use the data, or if it doesn't exist assume it's the first object and create the data.

import random

class MyClass():
    info = 0

    def __init__(self):
        if self.info == 0:
            #configure things
            print(f"Configuring class info on first use.")
            MyClass.info = random.randint(1000, 100000)
        print(f"Created new object {id(self)}.  Class info is {self.info}")

[MyClass(), MyClass(), MyClass()]
Output:
Configuring class info on first use. Created new object 4366991120. Class info is 81133 Created new object 4366990976. Class info is 81133 Created new object 4367286480. Class info is 81133
Reply


Messages In This Thread
RE: function that run once for all objects - by bowlofred - Sep-30-2021, 08:10 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  AWS Boto3 - objects function PythonDialer 0 219 May-19-2024, 11:50 AM
Last Post: PythonDialer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020