我正在尝试从封装类中获取封装的类抓取上下文,例如标签。一种方法是传递标签,就像我在下面显示的实例化期间一样。
我已经看到日志模块如何允许您使用 get_logger 函数订阅子日志,并且我想要一个 get_context() 函数。有没有办法做到这一点?
如果这个标签的传递达到一个级别,就像下面的 YetAnotherClass,它似乎可以容忍......但是如果你必须将它传递到 3 或 4 个级别 --- 这就是我真正想要另一个解决方案来传递这个标签的地方。
我应该以不同的方式思考这个问题吗?这是一些示例代码:
class RootClass(object) :
def __init__(self) :
self.ac = AnotherClass('root_class_context')
def do_insert(self) :
""" use DataTableMgr class to update table """
self.ac.insert_to_table('field1', 'field2', 'field3')
class AnotherClass(object) :
def __init__(self, label) :
self.context = label
self.dtm = DataTableMgr('arg1','arg2', 'arg3', 'arg4', self.context)
def insert_to_table(self, field1, field2, field3) :
""" insert args to database using DataTableMgr """
self.dtm.insert_to_table(field1, field2, field3)
class YetAnotherClass(object) :
def __init__(self) :
self.dtm = DataTableMgr('arg1','arg2', 'arg3', 'arg4', 'yetanother_context')
def do_insert(self) :
""" use DataTableMgr class to update table """
self.dtm.insert_to_table('field1', 'field2', 'field3')
class DataTableMgr(object) :
""" manage insert, updates to some table """
def __init__(self, arg1, arg2, arg3, arg4, user_id) :
self.context = user_id
def insert_to_table(self, field1, field2, field3) :
""" insert fields to table, while updating user id"""
print( "inserting...(pretending to be updating sql database)")
print(field1, field2, field3, self.context)
print
if __name__ == "__main__" :
#instantiate a class once removed from the inserting class and do insert
rc = RootClass()
rc.do_insert()
#instantiate a class directly accessing the class for inserting
yac = YetAnotherClass()
yac.do_insert()
#note how the context changes
print
print("Notice how the context changes? "
".. is there a better way to pass around this context information?")