zoukankan      html  css  js  c++  java
  • 关于python导包问题

    讨论采用 * 模糊导入或者 单独导入变量 会在不同文件生成不同的对象
    .a
    └── mypackage
        ├── a.py
        ├── b.py
        ├── c.py
     

    b.py内容如下

    import c
    
    def b():
        print("b方法开始")
        print(c.config)
        print(id(c.config))

    c.py内容如下

    config = "ONCE"

    a.py内容如下

    import b
    import c
    
    def a():
        print(c.config)
        c.config = "TWO"
        print(c.config)
        print(id(c.config))
        print("a方法执行完毕")
    
    a()
    b.b()

    执行a.py,输出

    ONCE
    TWO
    2492322048184
    a方法执行完毕
    b方法开始
    TWO
    2492322048184

    id值相同,意味着此时a,b文件共用一个对象

    ===========================我是分割线===========================

    但是。。。假如

    ======a.py======
    import b
    from c import config
    
    def a():
        global config
        print(config)
        config = "TWO"
        print(config)
        print(id(config))
        print("a方法执行完毕")
    
    a()
    b.b()
    ======b.py====== 
    from c import config
    
    def b():
        print("b方法开始")
        print(config)
        print(id(config))
    
    ======c.py====== 
    config = "ONCE"

    那么此时a.py输出为

    ONCE
    TWO
    1813891082424
    a方法执行完毕
    b方法开始
    ONCE
    1813894255144

    id值不同,意味着不是同一个对象

    因此如果需要使用可修改配置文件的全局变量,需要用文件名方式导入,将其当作一个全局类使用

    单独导入或者模糊导入会拥有不同的id和引用类型

  • 相关阅读:
    light oj 1007
    51nod 1298 圆与三角形
    codeforces 899C Dividing the numbers
    zznu 1996 : 正三角形和圆的爱情
    zznu 2081 : 舰队管理
    zzun 2076 : 三花聚顶神功
    zznu 2054 : 油田
    机械设备--第九届省赛--深搜
    设计模式-单例模式、工厂模式
    Spring Boot 遇到空指针
  • 原文地址:https://www.cnblogs.com/7134g/p/11546582.html
Copyright © 2011-2022 走看看