例如: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()有什么办法可以做到这一点?
1 回答
凤凰求蛊
TA贡献1825条经验 获得超4个赞
您可以通过使用 astaticmethod而不是属性、传递调用者的clsorself并测试它是否是类对象来执行您想要的操作:
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 中更常见的是为每个记录器而不是每个类定义一个模块。除非从每个类的记录器中获得真正的价值,否则我会在每个模块中使用一个。
添加回答
举报
0/150
提交
取消