Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

python - What is variable shadowing?

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

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

    def doStuff(self):
        print(self.i)

class Child(Parent, object):

    def __init__(self):
        super(Child, self).__init__()
        self.i = 7

class Main():

    def main(self):
        m = Child()
        print(m.i) #print 7
        m.doStuff() #print 7

m = Main()
m.main()

Output will be:

$ python Main.py 
7
7

That answer then compares it to a similar program in Java:

The reason is because Java's int i declaration in Child class makes the i become class scope variable, while no such variable shadowing in Python subclassing. If you remove int i in Child class of Java, it will print 7 and 7 too.

What does variable shadowing mean in this case ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What does variable shadowing mean in this case?

Variable shadowing means the same thing in all cases, independent of context. It's defined as when a variable "hides" another variable with the same name. So, when variable shadowing occurs, there are two or more variables with the same name, and their definitions are dependent on their scope (meaning their values may be different depending upon scope). Quick example:

In [11]: def shadowing():
    ...:     x = 1
    ...:     def inner():
    ...:         x = 2
    ...:         print(x)
    ...:     inner()
    ...:     print(x)
    ...:

In [12]: shadowing()
2
1

Note that we call inner() first, which assigns x to be 2, and prints 2 as such. But this does not modify the x at the outer scope (i.e. the first x), since the x in inner is shadowing the first x. So, after we call inner(), and the call returns, now the first x is back in scope, and so the last print outputs 1.

In this particular example, the original author you've quoted is saying that shadowing is not occurring (and to be clear: not occurring at the instance level). You'll note that i in the parent takes on the same value as i in the child. If shadowing occurred, they would have different values, like in the example above (i.e. the parent would have a copy of a variable i and the child would have a different copy of a variable also named i). However, they do not. i is 7 in both the parent and child. The original author is noting that Python's inheritance mechanism is different than Java's in this respect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...