What is variable shadowing?

后端 未结 3 629
夕颜
夕颜 2021-01-15 21:23

https://stackoverflow.com/a/37657923/8061009 states that for the program:

class Parent(object):
    i = 5;
    def __init__(self):
        self.i = 5

    de         


        
3条回答
  •  遥遥无期
    2021-01-15 21:31

    In Java, methods and fields are fundamentally different things, operating by entirely different rules. Only methods are inherited by subclasses; fields are specific to the class that declared them. If a subclass declares a field with the same name as one in a parent class, they are entirely unrelated; methods of the parent class continue to access the parent's version, and methods of the child class access its version. This is what is referred to as shadowing. If the parent class actually wanted to make its field available to children, it would have to define getter/setter methods for it.

    In Python, there is no such distinction - methods are basically fields whose value happens to be a function. Furthermore, all of the fields from the entire inheritance hierarchy are stored in a single namespace (typically implemented as a dict attribute named __dict__). If the child and parent use the same name for something, they are necessarily referring to the same object.

提交回复
热议问题