相关疑难解决方法(0)

__getattr__与__getattribute__之间的区别

我想知道何时使用__getattr__或__getattribute__.该文件提到了__getattribute__适用于新样式类.什么是新式课程?

python getattr getattribute

378
推荐指数
8
解决办法
12万
查看次数

为什么字典排序是非确定性的?

我最近从Python 2.7切换到Python 3.3,似乎在Python 2中,字典键的排序是任意的但是一致的,在Python 3中,用例如获得的字典的键的排序vars()看起来是非确定性的.

如果我跑:

class Test(object): pass
parameters = vars(Test)
print(list(parameters.keys()))
Run Code Online (Sandbox Code Playgroud)

在Python 2.7和Python 3.3中,然后:

  • Python 2.7一直给我

    ['__dict__', '__module__', '__weakref__', '__doc__']
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用Python 3.3,我可以得到任何随机顺序 - 例如:

    ['__weakref__', '__module__', '__qualname__', '__doc__', '__dict__']
    ['__doc__', '__dict__', '__qualname__', '__module__', '__weakref__']
    ['__dict__', '__module__', '__qualname__', '__weakref__', '__doc__']
    ['__weakref__', '__doc__', '__qualname__', '__dict__', '__module__']
    
    Run Code Online (Sandbox Code Playgroud)

这种非决定论来自哪里?为什么会这样

list({str(i): i for i in range(10)}.keys())
Run Code Online (Sandbox Code Playgroud)

......在跑步之间保持一致,总是给予

['3', '2', '1', '0', '7', '6', '5', '4', '9', '8']
Run Code Online (Sandbox Code Playgroud)

......?

python dictionary non-deterministic python-3.x python-3.3

37
推荐指数
2
解决办法
7794
查看次数