[英]Why import class from another file will call __init__ function?
The structure of the project is: 该项目的结构是:
project 项目
- main.py - main.py
- session.py - session.py
- spider.py - spider.py
There is a class in session.py: session.py中有一个类:
import requests
class Session:
def __init__(self):
self.session = requests.Session()
print('Session created.')
And another class in spider.py: 而spider.py中的另一个类:
from session import Session
class Spider:
def __init__(self, sess: Session = Session()):
print('Spider created.')
When I import class Spider
from spider.py in main.py like this: 当我从main.py中的spider.py导入类Spider
,如下所示:
from spider import Spider
if __name__ == '__main__':
print('Main function.')
spider = Spider()
And run main.py, I get: 并运行main.py,我得到:
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. 我认为__init__
是初始化实例时使用的初始函数,但在这种情况下,当在spider.py中导入Session
时Session
调用Session
的__init__
函数。 I think it must be related to the default value of __init__
function in spider.py, but why? 我认为它必须与spider.py中__init__
函数的默认值相关,但为什么呢?
The default values of parameters get evaluated only once in python. 参数的默认值只在python中计算一次。 This is documented here and also here as stated by JETM . 这是记录在这里 ,并在这里按规定JETM 。
Therefore a isntance of Session
is created when you import spider
as default value for the sess
parameter of the spiders __init__
method. 因此,当您将spider
作为spiders __init__
方法的sess
参数的默认值导入时, Session
创建Session
的isntance。
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: 如果你不希望这样的行为你可以使用None
作为默认值,并且如果没有像MatsLindh和FHTMitchel所指出的那样提供其他值,则在__init__
方法内创建Sesssion
实例:
...
def __init__(self, sess: Session = None):
if sess is None:
sess = Session()
print('Spider created.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.