从类方法中调用实例方法,在python3中允许,在python 2中不允许?

问题描述 投票:1回答:1

以下代码段在python2中给出了错误,但在python3中没有错误

class Steps(object):
    def step(self, msg="Default"):
        if not hasattr(self, "funky_attr"):
            print('No attr')
        print(self)
        print(msg)

class FirstTest(Steps):
    @classmethod
    def test_setup(cls):
      cls.step("This is the message")

if __name__ == '__main__':
    C = FirstTest()
    C.test_setup()

使用python 2会产生错误:

TypeError:未绑定方法step()必须使用CifsTest实例调用作为第一个参数(改为使用str实例)

虽然使用python 3,它运行良好:

无属性

这是消息#注意,这里的“自我”是str

默认

这是正确的行为吗?

Python3允许从类方法中调用实例方法?

python python-3.x python-2.7 class-method
1个回答
0
投票

在Python 3中,方法是常规函数对象(不是“未绑定方法”的实例),因此它们不会检查第一个参数是否是该类的实例。

不确定为什么认为此更改很重要(可能是均匀性或性能,但您观察到的结果似乎是此选择的不良副作用。

© www.soinside.com 2019 - 2024. All rights reserved.