简体   繁体   中英

Accessing globals of subclass' module

I've recently decided to write a helper class to output some information from a module. It looks like this:

class VarPrinter(object):
    @classmethod
    def save(cls):
        globals = cls.globals
        #do stuff with globals...
            for i in things_to_output:
            ...

# subclass in another module
# e.g. in foo.py
class FooPrinter(VarPrinter):
    things_to_output = ('foo', 'bar')
    globals = globals()

The question is: is there a way to get globals() array of a module where VarPrinter is subclassed so that I don't need to pass it explicitly like globals = globals() . In other words, the solution I want behaves as if I repeated the code of baseclass in a module of subclass. Initially I thought eval would help to do this but this was not the case.

您可以使用cls.__module__并在sys.modules查找它。

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