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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值