私信  •  关注

Patrick Haugh

Patrick Haugh 最近创建的主题
Patrick Haugh 最近回复了
3 年前
回复了 Patrick Haugh 创建的主题 » Python在try except finally中与返回值混淆

您遇到了标识符和值之间的差异。 num += 1 正在创建一个新的 int 对象并指定 num 标识符来指向它。这并不会改变现状 智力 标识符已指向的对象。(对于较小的值 智力 对象被缓存,但这是一个实现细节)

在下面的代码中,您可以看到对对象进行变异的操作的区别:

def y():
    l = []
    try:
        raise Exception
    except Exception:
        print("except")
        l.append(1)
        return l
    finally:
        print("finally")
        l.append(2)

print(y())
# except
# finally
# [1, 2]
6 年前
回复了 Patrick Haugh 创建的主题 » 如何修复Python错误:attribute error:type object X没有属性Y

当你跑的时候 ID() 的新实例 ID 类已创建。 __init__ 打电话给 other_number 该实例的方法,该方法指定实例属性 the_other_number . 因为您不在任何地方保存该实例,所以通过指定 ID() ,立即收集垃圾。这个 身份证件 类不变。

当你跑的时候 ID_2() ,您将创建 ID_2 上课和跑步 __初始__ 方法。这就叫 update_number 方法,它检查 ID._the_other_number . 身份证件 没有 对方号码 属性,因此引发错误。

阅读 Python tutorial on Classes ,并特别注意类对象和实例对象之间的区别。

5 年前
回复了 Patrick Haugh 创建的主题 » 如何转换需要用户输入才能在不协调bot中工作的python代码?

有两种方法可以编写此命令:一种是在问题中使用“对话”样式

from discord.ext.commands import Bot

bot = Bot("!")

def check(ctx):
    return lambda m: m.author == ctx.author and m.channel == ctx.channel

async def get_input_of_type(func, ctx):
    while True:
        try:
            msg = await bot.wait_for('message', check=check(ctx))
            return func(msg.content)
        except ValueError:
            continue

@bot.command()
async def calc(ctx):
    await ctx.send("What is the first number?")
    firstnum = await get_input_of_type(int, ctx)
    await ctx.send("What is the second number?")
    secondnum = await get_input_of_type(int, ctx)
    await ctx.send(f"{firstnum} + {secondnum} = {firstnum+secondnum}")

二是使用 converters 接受参数作为命令调用的一部分

@bot.command()
async def calc(ctx, firstnum: int, secondnum: int):
    await ctx.send(f"{firstnum} + {secondnum} = {firstnum+secondnum}")
6 年前
回复了 Patrick Haugh 创建的主题 » 我的变量不工作,使用discord.py(python)得到一个奇怪的错误代码

Client.wait_for_message 是一次联程,必须是 await 预计起飞时间:

responses = await client.wait_for_message(author=message.author)

同样,你的 send_messages 缺少一个 等待 ,您应该使用 asyncio.sleep 结束 time.sleep 以免阻塞事件循环。

6 年前
回复了 Patrick Haugh 创建的主题 » python创建自定义魔术方法
def logging(cls):
  return cls.__logging__()

class Cls:
  def __logging__(self):
    return "__logging__ called"