【问题标题】:Calling instance method from class method, allowed in python3, disallowed in python 2?从类方法调用实例方法,在python3中允许,在python 2中不允许?
【发布时间】:2019-11-04 07:29:44
【问题描述】:

以下代码 sn-p 在 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 运行良好:

无属性

这是消息 # 注意这里的'self'是str

默认

这是正确的行为吗?

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

【问题讨论】:

    标签: python python-3.x python-2.7 class-method


    【解决方案1】:

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

    不知道为什么认为此更改很重要(可能是一致性或性能),但您观察到的结果看起来像是此选择的不良副作用。

    【讨论】:

    • 感谢您的解释。几天前,当我遇到此链接stackoverflow.com/questions/16427379/… 时,我需要这样做(从classmethod 调用实例方法),看来,这并不完全正确
    • @mittal 在那个问题中,答案建议进行更改,因此实例方法将调用类方法。 (说明中的since it is an instance method部分适用于__init__()
    • @tevemadar 是的,我可以这样做,但我不拥有大师班的代码 :) 但现在我知道使用 python 3 我可以传递任何东西(甚至没有)并调用实例方法classmethod
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 2014-05-21
    • 1970-01-01
    • 2017-10-01
    • 2016-03-23
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多