栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何知道在Python中实例化对象的位置?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何知道在Python中实例化对象的位置?

在不考虑为什么要这样做的优点的情况下,可以采用以下方法:

# assume the file is saved as "temp.py"import inspectclass RegisteredObject(object):    def __new__(cls, *args, **kwargs):        new_instance = super(RegisteredObject, cls).__new__(cls, *args, **kwargs)        stack_trace = inspect.stack()        created_at = '%s:%d' % ( stack_trace[1][1], stack_trace[1][2])        new_instance.created_at = created_at         return new_instance    def get_file_of_object_creation(self):        return self.created_atclass MyObject(RegisteredObject):    passdef create_A():    return MyObject()def create_B():    return MyObject()if __name__ == '__main__':    t1 = create_A()    t2 = create_B()    t3 = create_A()    t4 = create_B()    t5 = MyObject()    print '"t1" was created at "%s"' % t1.get_file_of_object_creation()    print '"t2" was created at "%s"' % t2.get_file_of_object_creation()    print '"t3" was created at "%s"' % t3.get_file_of_object_creation()    print '"t4" was created at "%s"' % t4.get_file_of_object_creation()    print '"t5" was created at "%s"' % t5.get_file_of_object_creation()

输出:

$ python temp.py"t1" was created at "temp.py:19""t2" was created at "temp.py:22""t3" was created at "temp.py:19""t4" was created at "temp.py:22""t5" was created at "temp.py:29"


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660732.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号