简体   繁体   中英

How can i print variable value defined in the method of a different class in python?

class ClassA:
    def __init__(self):

        def val1(self):
            a = 1
            b = 2
            return b

class ClassB (ClassA):
    def val2(self):
        print(b) # b has been defined in ClassA var1 method 

The following answer is predicated on the assumption that your indentation is wrong and that val1 is a method of ClassA , not a nested function in ClassA.__init__ . In the latter case, since the function is not returned anywhere, there is absolutely nothing you can do, so I will disregard that possibility.

To get the value, you have to call the method which returns it. You can not access the local variables within a method outside it. Those variables only exist for the duration of a call anyway, and get recreated every time:

def val2(self):
    print(self.val1())

Or more verbosely:

def val2(self):
    b = self.val1()
    print(b)

An alternative is to make the value non-local to begin with, and use it as a regular attribute:

class ClassA:
    def __init__(self):
        self.b = 0

    def val1(self):
        self.a = 1
        self.b = 2

class ClassB (ClassA):
    def val2(self):
        print(self.b) # prints 0 until `self.val1` is called. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM