What is variable shadowing?

后端 未结 3 663
夕颜
夕颜 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:38

    Variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. Then the variable in the scope that you are in shadows (hides/masks) the variable in the outer scope.

    In the above code the variable i is being initialized in both the super class and the child class. So the initialization in the super class will be shadowed by the initialization in the child and class.

    m = Child() #we initialized the child class with i=7
    print(m.i) #eventhough we are calling a method in the super class the value of i in the super class is shadowed by the value we initialized the instance of the child class (m)
    m.doStuff() #same thing here
    

提交回复
热议问题