Why import class from another file will call __init__ function?

2024/11/18 1:32:47

The structure of the project is:

project
- main.py
- session.py
- spider.py

There is a class in session.py:

import requestsclass Session:def __init__(self):self.session = requests.Session()print('Session created.')

And another class in spider.py:

from session import Sessionclass Spider:def __init__(self, sess: Session = Session()):print('Spider created.')

When I import class Spider from spider.py in main.py like this:

from spider import Spiderif __name__ == '__main__':print('Main function.')spider = Spider()

And run main.py, I get:

Session created.
Main function.
Spider created.

It confuses me. I think __init__ is the initial function used when initializing an instance, but in this case the __init__ function of Session is called when Session is imported in spider.py. I think it must be related to the default value of __init__ function in spider.py, but why?

Answer

The default values of parameters get evaluated only once in python. This is documented here and also here as stated by JETM.

Therefore a isntance of Session is created when you import spider as default value for the sess parameter of the spiders __init__ method.

If you do not wish such a behavior you can use None as default value and create the Sesssion instance inside the __init__ method if no other value was provided as pointed out by MatsLindh and FHTMitchel like this:

...
def __init__(self, sess: Session = None):if sess is None:sess = Session()print('Spider created.')
https://en.xdnf.cn/q/71117.html

Related Q&A

Flask: login session times out too soon

While editing a record, if there is a long wait of let say a few minutes (getting coffee) and then coming back to press the save (POST), I get redirected to the main page to login instead and the data …

Activate virtual environement and start jupyter notebook all in batch file

I created the following batch file: jupyter_nn.bat. Inside file I have:cd "C:\My_favorite_path" activate neuralnets jupyter notebookSo the goal is to activate conda virtual environment and s…

several contour plots in the same figures

I have several 3d functions. I would like two plot the contour plots of them in the same figure to see the difference between them. I expect to see some crossings between contours of two functions. Her…

how to detect all the rectangular boxes in the given image

I tried to detect all the rectangles in image using threshold, canny edge and applied contour detection but it was not able to detect all the rectangles. Finally, I thought of detect the same using hou…

Python Pandas Series failure datetime

I think that this has to be a failure of pandas, having a pandas Series (v.18.1 and 19 too), if I assign a date to the Series, the first time it is added as int (error), the second time it is added as …

Remove a dictionary key that has a certain value [duplicate]

This question already has answers here:Removing entries from a dictionary based on values(4 answers)Closed 10 years ago.I know dictionarys are not meant to be used this way, so there is no built in fun…

Get names of positional arguments from functions signature

Using Python 3.x, Im trying to get the name of all positional arguments from some function i.e: def foo(a, b, c=1):returnRight now Im doing this: from inspect import signature, _empty args =[x for x, p…

Emacs Python-mode syntax highlighting

I have GNU Emacs 23 (package emacs23) installed on an Ubuntu 10.04 desktop machine and package emacs23-nox installed on an Ubuntu 10.04 headless server (no X installed). Both installations have the sam…

programmatically edit tab order in pyqt4 python

I have a multiple textfield in my form. My problem is the tab order is wrong. Is there a way to edit tab order in code? Just like in QT Designer.thanks.

Getting the parent of a parent widget in Python Tkinter

I am trying to get the parent of a widget then get the parent of that widget. But Everytime I try to I get a error.Error:AttributeError: str object has no attribute _nametowidgetWhy is it giving me tha…