Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么可以';难道你不认为魔术方法和它们的内置方法完全一样吗?_Python_Python 3.x - Fatal编程技术网

Python 为什么可以';难道你不认为魔术方法和它们的内置方法完全一样吗?

Python 为什么可以';难道你不认为魔术方法和它们的内置方法完全一样吗?,python,python-3.x,Python,Python 3.x,我正在制作一个irc bot,大量脚本返回的内容非常适合f'{label}:{value}'格式。因此,我创建了一个Result类,并为其提供了\uuuuuuuuuuuuuuuuuuuu字节方法,因为我以前使用过它,它工作得很好。或者我是这么想的 WHITE = '00' BLACK = '01' DARK_BLUE = '02' DARK_GREEN = '03' RED = '04' DARK_RED = '05' PURPLE = '06' ORANGE = '07' YELLOW = '

我正在制作一个irc bot,大量脚本返回的内容非常适合
f'{label}:{value}'
格式。因此,我创建了一个Result类,并为其提供了
\uuuuuuuuuuuuuuuuuuuu字节
方法,因为我以前使用过它,它工作得很好。或者我是这么想的

WHITE = '00'
BLACK = '01'
DARK_BLUE = '02'
DARK_GREEN = '03'
RED = '04'
DARK_RED = '05'
PURPLE = '06'
ORANGE = '07'
YELLOW = '08'
GREEN = '09'
TEAL = '10'
CYAN = '11'
BLUE = '12'
PINK = '13'
GREY = GRAY = '14'

def colorize(msg, color):
  """Add color code to message"""
  return f'{color}{msg}'

class Result:

  def __init__(self, label, value, color=RED):
    self.repr = f'{colorize(label, color)}: {value}'

  def __bytes__(self, encoding='utf-8'):
    return self.repr.encode(encoding)

def join_results(results, sep=' '):
  """Break results into a maximum of 350 bytes per line"""
  sep = sep.encode() if isinstance(sep, str) else sep
  if not isinstance(sep, bytes):
    raise TypeError('sep must be bytes or str')
  if (not isinstance(results, list)) or (not results):
    return []
  seplen = len(sep)
  x = bytes(results[0], encoding='utf-8')
  ret = []
  for result in results[1:]:
    y = bytes(result)
    msglen = len(y) + len(x)
    if (msglen + seplen) > 350:
      ret.append(x.decode())
      x = y
    else:
      x = sep.join((x, y))
  return ret + [x.decode()]  
在上面的代码中,对结果调用字节会引发类型错误:

>>> bytes(r, encoding='utf-8')
Traceback (most recent call last):
  File "<pyshell#265>", line 1, in <module>
    bytes(r, encoding='utf-8')
TypeError: encoding without a string argument   
>>字节(r,encoding='utf-8')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
字节(r,encoding='utf-8')
TypeError:编码时没有字符串参数
不过,在某些情况下,我希望
join\u results
也能处理字符串列表。将join_results中的x更改为
x=bytes(str(results[0]),编码为='utf-8')
而不是
x=bytes(results[0],编码为='utf-8')
很简单,但是为什么呢?然后我必须在结果中添加_ustr_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu


我还检查了其他一些东西,比如
\uuuuu int\uuuu
,它的内置函数也接受一个
base
参数,用于将字符串转换为int。但与
\uuu bytes\uuuu
类似,它也抛出
类型错误:int()无法转换具有显式base的非字符串。错误信息很清楚,所以我要重申:我不是问它为什么抛出错误。我想问的是,为了让
\uu str\uuuuuuu
\uuuu bytes\uuuuu
\uuu int\uuuuu
像内置函数一样工作,被迫跳转的逻辑是什么。

如果我理解正确,你会遇到一个问题,即
编码的
字节不能作为身份函数工作

您认为您被迫将
字节
转换为
str
,只是为了重新编码它们,但事实并非如此。您只需要不尝试编码字节

您可以编写一个小助手函数来解决此问题,该函数将扩展该功能以满足您的需要:

coerce_to_bytes = lambda x: x if isinstance(x, bytes) else bytes(x, encoding='utf-8')
s = "foo"
b = b"bar"
print(coerce_to_bytes(s), coerce_to_bytes(b))
>>> b'foo' b'bar'

这正是你所期望的。至少对于字节和字符串。我想如果你需要处理所有类型,那么逻辑会有点复杂,但不是那么复杂。

嗯,对不起,你是在问为什么
字节(r,encoding='utf-8')
需要
r
成为
str
?也许是因为编码其他东西真的没有意义。您是否希望
字节
上的
字节
成为标识,而不考虑
编码
参数?我想这是一个设计决定。用户试图做一些无意义的事情,我们是把它们弄错了还是默默地忽略了它。顺便说一句,如果这是你的问题,你不需要提供
\uuuu str\uuuu
,我可以为你的问题发布一个“解决方法”/解决方案。@luk32第三个选项(这是PHP有时需要的):在幕后做一些意想不到的事情,这会混淆用户并返回结果。@leaf我认为这是JS的方式。失败不是选项。=]运行此命令时,我收到一个语法错误:
返回f'{color}{msg}'
,您在那里试图做什么,格式化字符串?一旦修好了,我也许能帮上忙。@Vincenzzochi