Mayank Gupta
Mayank Gupta

Reputation: 171

How can I check if a class has been instantiated in Python ?

In one of my classes, I am printing data from another class that is yet to be initialized.I only want to print that data once the class has been initialized.Is there any way check if the class has been instantiated?

Upvotes: 5

Views: 10057

Answers (3)

Tahlor
Tahlor

Reputation: 1870

Two functions that return true if you pass an undeclared class, and false if it is instantiated:

import inspect
inspect.isclass(myclass)

or

isinstance(myclass, type)

In general, if it's not a type (i.e. undeclared class), it's an instantiated type.

Upvotes: 14

Whirlpool Pack
Whirlpool Pack

Reputation: 91

Simply add a variable into the class to be made, like this:

class tobeinitiated():
    initiated=False
    def __init__(self):
        global initiated
        tobeinitiated.initiated = True

Then, where you need the information:

global initiated #(if in class)
if tobeinitiated.initiated:
    #do the stuff you need to do

Hope this helps. :)

Upvotes: 1

matiit
matiit

Reputation: 8017

You can add a counter of instances in the constructor for example.

Upvotes: -2

Related Questions