我刚刚发现的位补元运算通过在Python 这个问题,并一直在努力来为它的实际应用中,如果没有,以确定它是否是普遍安全的重载操作(通过重写__invert__方法)用于其他用途.问题中给出的示例失败了TypeError,并且提供的链接看起来非常令人生畏.这里有一些摆弄~使用:
from bitstring import BitArray
x = 7
print(~x)
# -8
print(BitArray(int=x, length=4).bin)
# '0111'
print(BitArray(int=~x, length=4).bin)
# '1000'
print(~~True, ~~False)
# 1 0
for i in range(-100, 100):
assert i + ~i == -1
assert i ^ ~i == -1
assert bool(i) == ~~bool(i)
Run Code Online (Sandbox Code Playgroud)
是否有任何针对该运营商,我应该知道的有效使用情况的例子吗?即使有,除了int?之外的类型覆盖此运算符通常是否可以接受?
python bit-manipulation operator-overloading tilde python-3.x
在Python int和floatPython中使用内置类型时,通常在输入可能不可靠的情况下采用异常处理:
def friendly_int_convert(val):
"Convert value to int or return 37 & print an alert if conversion fails"
try:
return int(val)
except ValueError:
print('Sorry, that value doesn\'t work... I chose 37 for you!')
return 37
Run Code Online (Sandbox Code Playgroud)
使用时是否需要注意任何突出的边缘情况str()?
def friendly_str_convert(val):
"Convert value to str or return 'yo!' & print an alert if conversion fails"
try:
return str(val)
except Exception: # Some specific Exception here
print('Sorry, that value doesn\'t work... I chose \'yo!\' for you!')
return 'yo!'
Run Code Online (Sandbox Code Playgroud)
我真的不喜欢使用广泛, …
给定带有print()语句的Python脚本,我希望能够运行脚本并在显示每个语句输出的每个语句后插入注释.要演示,请将此脚本命名为example.py:
a, b = 1, 2
print('a + b:', a + b)
c, d = 3, 4
print('c + d:', c + d)
Run Code Online (Sandbox Code Playgroud)
期望的输出是:
a, b = 1, 2
print('a + b:', a + b)
# a + b: 3
c, d = 3, 4
print('c + d:', c + d)
# c + d: 7
Run Code Online (Sandbox Code Playgroud)
这是我的尝试,适用于上面的简单示例:
import sys
from io import StringIO
def intercept_stdout(func):
"redirect stdout from a target function"
def wrapper(*args, **kwargs):
"wrapper function …Run Code Online (Sandbox Code Playgroud)