nested classes in Python

前端 未结 2 1684
攒了一身酷
攒了一身酷 2020-12-25 08:38

Dealing with classes (nested etc) does not look easy in Python, surprisingly! The following problem appeared to me recently and took sever

2条回答
  •  长情又很酷
    2020-12-25 09:43

    The code executed in a method runs in the local scope of that method. If you access an object that is not in this scope, Python will look it up in the global/module scope, NOT in the class scope or the scope of any enclosing class!

    This means that:

    A.a = 'a_b'
    

    inside C.B.__init__ will set the class attribute of the global A class, not C.A as you probably intended. For that you would have to do this:

    C.A.a = 'a_b'
    

    Also, Python will not call parent methods if you override them in subclasses. You have to do it yourself.

    The scoping rules mean that if you wanted to call the __init__ method of the parent class inside C.B.__init__, it has to look like this:

    C.A.__init__(self)
    

    and NOT like this:

    A.__init__(self)
    

    which is probably what you've tried.

提交回复
热议问题