canadadry
canadadry

Reputation: 8443

Is it possible for a method of a class to be invoked first before the init constructor?

My class:

from django.contrib.admin.views.main import ChangeList
class MyChangeList(ChangeList):
    def __init__(self, *args):
        ...

    def get_query_set(self):
        ...

I added logs in both __init__ and get_query_set and I have noticed that the log output in the latter gets printed out (but none for the one in __init__. Is this possible ?

Upvotes: 1

Views: 83

Answers (1)

phihag
phihag

Reputation: 287865

The __init__ function can call arbitrary methods itself, and construction of objects in Python can also be complicated with __new__, so make sure both outputs refer to the same object (for example, by including id(self) in the output).

To find out who called get_query_set, you can use traceback.print_stack:

import traceback
traceback.print_stack()

Upvotes: 3

Related Questions