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 中更常见的是为每个记录器而不是每个类定义一个模块。除非从每个类的记录器中获得真正的价值,否则我会在每个模块中使用一个。
添加回答
举报