カプセル化されたクラスから、ラベルのように、カプセル化されたクラスがコンテキストを取得しようとしています。これを行う 1 つの方法は、以下に示すようにインスタンス化中のように、ラベルを渡すことです。
ロギング モジュールを使用すると、get_logger 関数を使用してサブログをサブスクライブできることを確認しましたが、get_context() 関数が必要です。これを行う方法はありますか?
このラベルの受け渡しが、下の YetAnotherClass のように 1 レベルになると、許容できるように見えますが、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?")