如何判断父类的函数是由子类的类方法或实例方法调用的?

例如:



class TestParent(object):

    # I need a function to be compatible with both classmethod and instance method.

    @property

    def log(cls, self=None):

        if "it's called from a child classmethod":

            return logging.root.getChild(cls.__class__.__module__ + '.' + cls.__class__.__name__)

        if "it's called from a child object":

            return logging.root.getChild(self.__class__.__module__ + '.' + self.__class__.__name__)




class TestChild(TestParent):

    @classmethod

    def test(cls):

        cls.logger.info('test')


    def test2(self):

        self.logger.info('test2')


child = TestChild()

child.test()

child.test2()

有什么办法可以做到这一点?


ABOUTYOU
浏览 135回答 1
1回答

凤凰求蛊

您可以通过使用 astaticmethod而不是属性、传递调用者的clsorself并测试它是否是类对象来执行您想要的操作:import logginglogging.basicConfig(level=logging.INFO)class TestParent(object):    # I need a function to be compatible with both classmethod and instance method.    @staticmethod    def logger(obj):        if isinstance(obj, type):            return logging.root.getChild(obj.__class__.__module__ + '.' + obj.__class__.__name__)        else:            return logging.root.getChild(obj.__class__.__module__ + '.' + obj.__class__.__name__)输出:INFO:builtins.type:testINFO:__main__.TestChild:test2话虽如此,在 Python 中更常见的是为每个记录器而不是每个类定义一个模块。除非从每个类的记录器中获得真正的价值,否则我会在每个模块中使用一个。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python