简体   繁体   中英

How to access an instance variable without running the function

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") .

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]

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