python类中方法的执行顺序-python类的执行顺序

博主编写Python脚本时,对类中打印语句执行顺序产生困惑。按理解,Python解释器应在类被调用时才执行内部代码,输出应先打印“Out”,但实际先打印“Middle”。经分析,因“Middle”打印语句不在函数定义内,会先被调用,可将其放入构造函数解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1586010002-jmsa.png

I was writing a small python script to understand a concept and got another confusion. Here's the code -

x = 5

y = 3

class Exp(object):

def __init__(self, x, y):

self.x = x

self.y = y

print("In",x, y, self.x, self.y)

print("Middle",x,y)

print("Out",x,y)

Exp(1,2)

The output is -

Middle 5 3

Out 5 3

In 1 2 1 2

Now, my concept was python interpreter starts reading and executing the code from the first line to last line. It executes the code inside a class only when it is "called", not when it is defined. So, the output should print "Out" first. But here it is printing "Middle" first. This should not happen, as python interpreter when first encounters "Middle" - it is within the definition, and thus should not be executed at that time. It should be executed only after reading the last line of code where the class "Exp" is called.

I searched on Google and StackOverflow for the solution but couldn't find one explaining it for the class.

Kindly help me understand where I'm getting it wrong...

解决方案

This odd behaviour happens because your print("Middle",x,y) is not inside a definition of a function, so it gets called before print("Out",x,y).

Your code is equivalent to:

x = 5

y = 3

class Exp(object):

def __init__(self, x, y):

self.x = x

self.y = y

print("In",x, y, self.x, self.y)

print("Middle",x,y)

print("Out",x,y)

Exp(1,2)

Whose output will be:

Middle 5 3

Out 5 3

In 1 2 1 2

One of the possible ways to correct this is to define print("Middle",x,y), say within the constructor.

x = 5

y = 3

class Exp(object):

def __init__(self, x, y):

self.x = x

self.y = y

print("In",x, y, self.x, self.y)

print("Middle",x,y)

print("Out",x,y)

Exp(1,2)

The output you will then get is:

Out 5 3

In 1 2 1 2

Middle 1 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值