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
在字典内部。对于比较两个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.