lhx2008
V2EX  ›  问与答

Python 面向对象的一个特性,要怎么解释呢

  •  
  •   lhx2008 · May 19, 2019 · 1594 views
    This topic created in 2730 days ago, the information mentioned may be changed or developed.

    有一个这样的写法

    class Test:
    
        def test_func(self):
            pass
    
        def __init__(self):
            self.test = Test.test_func
    
    
    if __name__ == "__main__":
        t = Test()
        t.test_func() # error
        t.test()
    

    Pycharm 已经傻掉了, 对于这段代码不会有任何错误提示,不过它运行起来是错误的

    t.test()
    TypeError: test_func() missing 1 required positional argument: 'self'
    

    是不是意味着解释器只对对象所属类中的方法自动传递了一个 self 参数,而属于对象实例的方法并没有

    5 replies  •  2019-05-20 10:16:25 +08:00
    zwzmzd
    zwzmzd
    May 19, 2019 via Android❤️1
    1
    bounded method 和 unbounded method 了解一下
    Wincer
    Wincer
    May 19, 2019
    2
    t.test_func 这里的 t 就是定义 test_func 参数里的 self,它等同于 Test.test_func(t)。
    lhx2008
    lhx2008
    OP
    May 19, 2019
    3
    @Wincer @zwzmzd
    py3 并没有 bounded 和 unbounded method,虽然在类实例调用函数的时候,3 的机制是继承 2 的

    但是事实上是把 test_func() 这个函数“绑定”到对象上了,从优先级来说,对象作用域应该比类作用域更高,不过,Python 的解释器似乎没有对于对象作用域内的函数进行补充处理
    Wincer
    Wincer
    May 19, 2019 via Android
    4
    为什么你会认为对象作用域要比类(class)的高?对象的行为是由定义的,而且我已经说过了,test_func 这个函数就是定义在 Test 这个 class 上的,你可以 dir(Test) 查看一下它的属性
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1656 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 13:28 · PVG 21:28 · LAX 05:28 · JFK 08:28
    ♥ Do have faith in what you're doing.