0

I thought I understood how this would work but apparently I don't. Take this example:

File 1 (sandbox.py):

from module1 import Testy

class Sandy(Testy):
    def run(self):
        print("This is value of x in Sandy: %d" % x)
        super(Sandy, self).mymet()

if __name__ == "__main__":
    x = 4
    test = Sandy()
    test.run()

File 2 (module1.py):

class Testy(object):
    def mymet(self):
        print("This is the value of x in Testy %d: " % x)

This is what I receive back in the console when running sandbox.py:

This is value of x in Sandy: 4
NameError: global name 'x' is not defined

Is the best/only way of doing this to pass the x argument explicitly to mymet() in the parent class?

2
  • you need to provide a reproducible example Commented Mar 22, 2018 at 17:52
  • That's not how scoping works. You can't access locals from other functions. Commented Mar 22, 2018 at 17:56

2 Answers 2

2

You need to pass it to both functions as a parameter:

class Testy(object):
    def mymet(self, x):
        print("This is the value of x in Testy %d: " % x)

class Sandy(Testy):
    def run(self, x):
        print("This is value of x in Sandy: %d" % x)
        super(Sandy, self).mymet(x)

if __name__ == "__main__":
    x = 4
    test = Sandy()
    test.run(x)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help, this is obviously a fundamental misunderstanding on my part. I believe in my case above I would only need to pass x into mymet() and wouldn't need to pass x into Sandy().run(). I guess I assumed this could be made available without explicitly passing it through - but seems I'm wrong.
@JPow You could bypass test.run(x) and call mymet directly with test.mymet(x) but you still need to pass it as a parameter.
-1

The issue is your base class Testy

the variable x is not defined in class scope and so it doesn't exist in your subclasses.

class Testy(object):
    self.x = 4
    def mymet(self):
        print("This is the value of x in Testy %d: " % self.x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.