如何判断父类的函数是由子类的classmethod或instance方法调用的



例如:


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()

有什么办法做到这一点吗?

您可以使用staticmethod而不是属性,传递调用方的clsself并测试它是否是类对象,从而完成您想要的操作:

import logging
logging.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:test
INFO:__main__.TestChild:test2

话虽如此,在Python中,更常见的做法是为每个记录器定义模块,而不是为每个类定义模块。除非每个类都有一个记录器,否则我会选择每个模块一个。

最新更新