我試圖從封裝類有一個封裝類抓取上下文,就像一個標籤。其中一種方法就是在實例化過程中傳遞標籤,如下所示。如何在Python中封裝類中訪問上下文標籤?
我見過的記錄模塊如何讓你訂閱與get_logger功能sublogs,我想有一個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?")
這裏的另一個想法,可能是使用環境變量...在基類中做到這一點:'進口操作系統; os.environ.setdefault('context','mylabel')'然後是'os.environ.get('context')'在模塊中。 – Voortuck 2013-02-21 22:47:06