Search code examples
pythonclassobjectprinting

Is it possible to call a variable within an argument from a class?


I'm trying to return the dictionary d that is within the argument bar from the class foo but the return I get is <function bar at 0x00000262763B2EE0>. Is this the best way to do this? I wrote an example code that I've written to represent what I'm working on which includes a much larger code. It seems to me like I may be going about this wrong, like I shouldn't be calling variables from outside the classes.

def bar():
    d = {'a':1, 'b':2}
    return d
class foo:
    def __init__(self, bar):
        self._bar = bar
    def p_dict(self):
        print(self._bar)

test_1 = foo(bar)

test_1.p_dict()

Solution

  • Try:

    def bar():
        d = {'a':1, 'b':2}
        return d
    class foo:
        def __init__(self, _bar):
            self._bar = _bar
        def p_dict(self):
            print(self._bar())
    
    test_1 = foo(bar)
    
    test_1.p_dict()