Calling a variable in another function without using global

I am trying to use a variable / list in a function that is defined in another function without making it global.

Here is my code:

def hi():
    hello = [1,2,3]
    print("hello")

def bye(hello):
    print(hello)

hi()
bye(hello)

I am currently receiving an error message saying that "hello" in "bye (hello)" is not defined.

How can i solve this?

+4
source share
4 answers

if you do not want to use a global variable, the best option is to call bye(hello)from hi().

def hi():
    hello = [1,2,3]
    print("hello")
    bye(hello)

def bye(hello):
    print(hello)

hi()
+3
source

You need to return hello from your method hi.

, , hi. , , .

Python:

http://gettingstartedwithpython.blogspot.ca/2012/05/variable-scope.html

hello hi, , hi, .

, hi :

def hi():
    hello = [1,2,3]
    return hello

, , hi :

hi_result = hi()

bye:

bye(hi_result)
+3

global.

def hi():
    hello = [1,2,3]
    print("hello")
    return hello

def bye(hello):
    print(hello)

hi()
bye(hi())
+2

, , -, - (. XY )

hi bye , . :

class MyGreetings(object):
    hello = [1, 2, 3]

    def hi(self):
        print('hello')

    def bye(self):
        print(self.hello)

:

global hello

def hi():
    global hello
    hello = [1,2,3]
    print("hello")

def bye():
    print(hello)

hi:

def hi():
    hello = [1,2,3]
    print("hello")
    return hello

def bye():
    hello = hi()
    print(hello)

hi:

def hi():
    hello = [1,2,3]
    print("hello")
    hi.hello = hello


def bye():
    hello = hi.hello
    print(hello)

, , , , - hi() bye(), hello:

import inspect
from textwrap import dedent


def hi():
    hello = [1,2,3]
    print("hello")

def bye():
    sourcelines = inspect.getsourcelines(hi)[0]
    my_locals = {}
    exec(dedent(''.join(sourcelines[1:])), globals(), my_locals)
    hello = my_locals['hello']
    print(hello)
0

Source: https://habr.com/ru/post/1613471/


All Articles