-3

Say I had two functions, one belonging to another like so.

def foo():
    def bar():
        print("im bar")
    print("im foo and can call bar")
print("i can call foo, but not bar?")

How would refer to or call bar? Would I do foo.bar()?

If bar were not a function like if bar = 1 then how would I access that?

I'm aware I could move bar out of foo but is there any other way?

jll123567
  • 85
  • 7
  • `bar` is not a member of `foo`. It is a local variable. To access the value outside you must return the value – juanpa.arrivillaga Mar 19 '19 at 15:54
  • 3
    `bar` only exists while `foo` is executing. As soon as `foo` ends, `bar` goes out of scope and ceases to exist. And that's just the first conceptual problem… – deceze Mar 19 '19 at 15:54
  • it sounds like this should be in a class with a staticmethod – gold_cy Mar 19 '19 at 15:56

1 Answers1

1

I don't think you can do what you want to do here, i.e. calling foo.bar and expect to get the result. You can, however, turn foo into a class and then try it that way.

Bob Fang
  • 6,963
  • 10
  • 39
  • 72