python 常见问题

1. 判定字典key相等,注意比较key是通过key的hash值

字典是python中很常见的一种类型。我们在很多都会用到

在一些情况下,我们有时需要自己定义key的类型。这时为了满足需求,我们可能需要修改__hash__和(__eq____cmp__)函数。此时注意这两种函数在

字典的运用情况不同。

如下面的例子:

class A:
      def __init__(self):
            self.a = ""
      def __eq__(self,other):
            if isinstance(other,A):
                return self.a == other.a
            return False
上面A是我们自定义的类型。我们重载了基类的两个函数__eq__。

a1 = A()
a1.a = "1"
test[a1] = 2

a = A()
a.a = "1"

print a in test
print a in test.keys()
此时返回是False 和 True。

但是如果

   class A:
      def __init__(self):
            self.a = ""
      def __hash__(self):
            return hash(a)
      def __eq__(self,other):
            if isinstance(other,A):
                return self.a == other.a
            return False


 此时就返回True,True了。 

在字典内部。对于比较两个key是否相同是比较他们的hash值。而对于test.keys()这个返回的是一个list对象,它是以来__eq__函数来比较的。

2. Python 包管理

Python包管理是Python项目中必须面临的问题,尤其是一些大的项目,如何管理包也是python程序员需要掌握的。

src/
    __init__.py
    A/
        __init__.py
        A1.py
        A2.py
    B/
        __init__.py
        B1.py
如上面结构,它是有三层包,顶层包是src,里面有两个其他的包A和B。python判断一个文件夹是否是一个包主要看其是否有__init__.py文件。在该文件中可以定义export到外部的模块。如src下的__init__.py文件如下,
from A import A1 as good
from A import A2 as bad

那么src同等目录下的python文件就可以直接from src  import good,bad。当然也可以直接from src.A import A1 as good达到同样的效果。

问题1:ValueError: Attempted relative import in non-package

对于直接运行的脚本不能通过相对路径来引用包,如上面有一个main.py文件需要引用模块good,只需要from src import good。

根据PEP328

Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy.
 If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports
 are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值