我们可以。但不要在家里这样做。说真的,1
对象在很多地方使用,我不知道这可能会破坏什么以及可能对您的计算机产生什么影响。我拒绝承担所有责任。但我发现了解这些事情很有趣。
The id功能 https://docs.python.org/3/library/functions.html#id给我们内存地址和ctypes module https://docs.python.org/3/library/ctypes.html让我们扰乱记忆:
import ctypes
ctypes.memmove(id(1) + 24, id(2) + 24, 4)
print(1 == 2)
x = 40
print(x + 1)
Output:
True
42
在线尝试一下! https://tio.run/##NYoxDoAgEAT7e8WVEI0RpLDhNUoixcEFicHXnyRqNTOb5bseOS0rF5FInEvFrd4cToCXEwWifAUVd2U0DmjdiN3t704DcImpKoPeo@3Z0KObv7X1n9EiDw。我在那里尝试过,因为无论如何,这些网站都必须受到保护,免受我们的黑客攻击。
更多解释/分析:
The memmove
从复制值2
对象进入1
目的。它们的大小各为 28 个字节,但我跳过了前 24 个字节,因为那是对象的引用计数、类型地址和值大小,我们也可以查看/验证:
import ctypes, struct, sys
x = 1
data = ctypes.string_at(id(x), 28)
ref_count, type_address, number_of_digits, lowest_digit = \
struct.unpack('qqqi', data)
print('reference count: ', ref_count, sys.getrefcount(x))
print('type address: ', type_address, id(type(x)))
print('number of digits:', number_of_digits, -(-x.bit_length() // 30))
print('lowest digit: ', lowest_digit, x % 2**30)
Output (在线尝试一下! https://tio.run/##bZDBbsMgEETvfMVeKuPIcdrkElnKn1RCBLCDmgCGtWp/vbuEpo2q@oIZ7cybJSx48e5wDHFd7S34iKBwCSY1kDBOCulcEmMznOCNaYmSfspESwPWDUIit5rPdQP7Y82i6YXykyNjnhJS62gSxbnpdjZR@F5oO1gk5eo/TcJypdR3BvQVaju5INUHr8ZxtFUDGVwzFgiIvCKGicYpA3dSBzTxxKXC7WCQlLtA1eqHM1eC70pdxlV/a9IqWcimH1epDr6HUr2r/ltny7dze7YorsYNeOE17HZweP2NKfuWjAf8@Q0amOEF9psNmdb1Cw):
reference count: 135 138
type address: 140259718753696 140259718753696
number of digits: 1 1
lowest digit: 1 1
引用计数增加getrefcount
打电话,但我不知道为什么到 3。无论如何,除了我们之外还有大约 134 个东西引用了1
对象,我们可能会把它们全部搞砸,所以……真的不要在家里尝试这个。
The "digits" refer to how CPython stores int
s as digits in base 230 https://github.com/python/cpython/blob/247480a21cb165efdacc346a2d589dfc27e18283/Include/cpython/longintrepr.h#L11-L39. For example, x = 2 ** 3000
has 101 such digits. Output for x = 123 ** 456
for a better test:
reference count: 1 2
type address: 140078560107936 140078560107936
number of digits: 106 106
lowest digit: 970169057 970169057