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和引用类型

  • 相关阅读:
    Linux_9/ RAID & LVM
    Linux_8/ fdisk, xfs_quota, edquota
    Linux_7/(chattr, lsattr), (setfacl, getfacl),su
    Linux_6/ Vim, Shell(下),(at, crond), (SUID, SGID, SBIT)
    Linux_5/ Vim, Shell(上)
    Linux_4/ |, (>, 2>, &>, >>, 2>>)
    Map集合的遍历
    List集合三种遍历方法
    MySQL安装
    排序法
  • 原文地址:https://www.cnblogs.com/7134g/p/11546582.html
Copyright © 2011-2022 走看看