How to access an instance variable without running the function

Viewed 37
class A:
    def __init__(self):
        self.num= [0]

    def b(self):
        print("Don't Run")
        self.num= [2]

obj = A()
obj.b()

print(obj.num)

>> Don't Run
>> [2]

Here I have a class and I want to access the instance variable self.num on function b. How can I access the variable without running the print("Don't Run").

2 Answers

If your goal is to avoid printing to the screen, you can redirect stdout using contextlib.redirect_stdout.

from contextlib import redirect_stdout
from os import devnull

...

with redirect_stdout(devnull):
  obj.b()

Another possibility is subclassing:

class B(A):
    def b(self, return _num=False):
        self.num = [2]
        if return_num:
            return self.num

So then,

>>> b = B()
>>> b.b(return_num=True)
>>> [2]
Related