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
#1
I create a class and I added a code that download a file and parse it in the __init__ .
for each object I create an object from my class it calls the init method.

what I want is to automatically call a certain function once for first object created and the remaining objects, they shall use the parameters that was parsed.
The init method is not going to do the job.

I know that I can do this by creating a method in the class and explicitly call it for first object only.
I was wondering if something already exists as magic method that can do the job implicitly.
Reply
#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
#3
I think you are asking if there is a way to automatically call a method ONLY for the first instance of a class. There is no such thing, but it is something you could write using a a class method to keep track

class Alpha():
	first = True

	def __init__(self):
		if self.__class__.first:
			print("I am first", self)
			self.__class__.first = False
		else:
			# Do not first stuff
			print("I am not", self)

[Alpha() for _ in range(3)]
.

If I am totally off base on my interpretation, write the python code to do what you want to do. Even if it doesn't work it is a good way to describe what you are thinking.
mr_byte31 likes this post
Reply
#4
You don't say why you want to do this. What is it you're trying to achieve, at a high level?
buran likes this post
Reply
#5
Thanks, I am aware about the __init__ method.
I was thinking there is a specific magic method for this purpose.
Reply
#6
You still haven't explained why you want to do this, or what's wrong with calling a method on the instance you want to use. It sounds like you've come up with a solution to a problem, but we don't know what the problem is, so are hard pressed to judge whether it's an appropriate one. On the face of it, it just seems odd to me to have instances know about each other.
Reply
#7
(Oct-14-2021, 03:22 PM)ndc85430 Wrote: You still haven't explained why you want to do this, or what's wrong with calling a method on the instance you want to use. It sounds like you've come up with a solution to a problem, but we don't know what the problem is, so are hard pressed to judge whether it's an appropriate one. On the face of it, it just seems odd to me to have instances know about each other.
the proplem was stated in the first few lines : I want to make the usage of the class much easier. The file is downloaded once for all objects. __init__ was not helping so I thought there is easier solution. I also didn't want the user of the class to call a specific method for getting the file downloaded.
Reply
#8
One thought - have an optional parameter in the definition that, when set designates that as your "first", don't need to modify other calls as the parameter is optional (named).
Reply
#9
I think having the __init__ method check a class variable should work great for this.
class Thing:
    parameters = None  # Stuff you want to read once and use many times

    @classmethod
    def init_parameters(cls):
        '''Load parameters from a file. All instances will share these parameters'''
        # Open file an read parameters
        cls.parameters = whatever()

    def __init__(self):
        if self.parameters is None:
            self.init_parameters()  # Initialize these class variables from a file.  Happens once.
        #Can use the parameters now
Sounds like all instances will share these parameters, so it makes sense to use a class variable to reference them.

If this is not applicable to your problem, why not? Can you explain please.
mr_byte31 likes this post
Reply
#10
@deanhystad, this seem to work fine !
thanks
Reply


Forum Jump:

User Panel Messages

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