I had an idea for a __first__
special method for a class. It would be run after __new__
and before __init__
the first time a specific object is instantiated but is not then run if you instantiate the object again. For example, if you run:
class Foo:
def __first__():
print('Inside __first__')
def __init__(self):
print('Inside __init__')
a = Foo()
b = Foo()
It would return:
Inside __first__
Inside __init__
Inside __init__
In order to try and create this particular syntax I decided to create a meta class so that you could simply add this syntax to a class of your choice. This was my final code for the meta class and it was the first time I have tried meta class syntax so I was interested in what you thought about my code:
class First(type):
_first = True
def __call__(cls, *args, **kwargs):
if cls._first:
cls._first = False
cls._oldinit = cls.__init__
def init(*args, **kwargs):
cls.__first__()
cls._oldinit(*args, **kwargs)
cls.__init__ = init
cls.__init__.__doc__ = cls._oldinit.__doc__
else:
cls.__init__ = cls._oldinit
return super(First, cls).__call__(*args, **kwargs)
first
be a class method? Perhaps that's not appropriate but context would be useful here. \$\endgroup\$__first__
is a class method but I suppose it could be \$\endgroup\$__first__
it will be run on the first time of D being run if either B or D hasFirst
set as its metaclass and then everything else will be normal \$\endgroup\$