小编use*_*030的帖子

类型提示中的子类

我想允许使用Python 3的类型提示来接受某个类的子类.例如:

class A:
    pass

class B(A):
    pass

class C(A):
    pass

def process_any_subclass_type_of_A(cls: A):
    if cls == B:
        # do something
    elif cls == C:
        # do something else
Run Code Online (Sandbox Code Playgroud)

现在输入以下代码时:

process_any_subclass_type_of_A(B)
Run Code Online (Sandbox Code Playgroud)

我得到一个PyCharm IDE提示'预期类型A,而不是类型[B].

如何在此处更改类型提示以接受A的任何子类型?

根据这个(https://www.python.org/dev/peps/pep-0484/#type-definition-syntax,"该参数也接受其类型是特定参数类型的子类型的表达式.") ,我明白我的解决方案(cls: A)应该有效吗?

python subclass type-hinting

20
推荐指数
4
解决办法
7873
查看次数

按<输入>上的Enter键提交错误的<form>(1页上的2个表单)

我在同一页面上有两种不同的形式.

<form action="" method="post" onsubmit="ajax_send('<?print $userid;?>',this.msg.value); return false;">
<input id="msg" autocomplete="off" type="text" name="msg" stlye="width: 80px;" autofocus="autofocus" placeholder="Chat here" />
<input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

<form action="?page=about&id=0#comments" method="post">
<textarea class="editbox" id="exitbox" placeholder="Write a comment ..." name="newcomment"></textarea>
<input type="submit" id="submit1" name="submit1"></div></div>
Run Code Online (Sandbox Code Playgroud)

现在当我输入内容<input id="msg"..>并按回车键时,它会提交第二个表单而不是第一个表单.

我错过了什么?

html php forms ajax input

1
推荐指数
1
解决办法
2025
查看次数

嵌套 if - 还有什么 Pythonic ?

这两个函数做同样的事情。

def function1(self):
    a = self.get_a()
    b = self.get_b()
    c = self.get_c()
    r = None

    if a:
        r = a
        if b:
            r = b
            if c:
                r = c
            else:
                print("c not set.")
        else:
            print("b not set.")
    else:
        print("a not set.")

    return r



def function2(self):
    a = self.get_a()
    b = self.get_b()
    c = self.get_c()
    r = None

    if not a:
        print("a not set.")
        return r

    r = a
    if not b:
        print("b not set.")
        return r

    r = b …
Run Code Online (Sandbox Code Playgroud)

python if-statement nested indentation pep

1
推荐指数
1
解决办法
2683
查看次数

将每个 pytest 测试函数包装到 try- except 中

我想将每个测试函数包装到 try- except 块中以执行 except 块中的代码。仅当测试失败时才应执行此代码。

我想在不改变测试功能的情况下实现这一点,而是使用某种装饰器/夹具。不幸的是我找不到任何例子。

我想要实现的目标的示例:

def test_1():
    some_method_that_might_throw_an_exception()
Run Code Online (Sandbox Code Playgroud)

run_only_if_exception_was_thrown()我有多个测试,如果测试抛出异常,所有测试都应该运行一个函数。我想在测试中不使用 try/catch 块来实现这一点。

我当前的方法是在固定装置内部使用来sys.last_value检查是否引发异常:

@pytest.fixture
def fix():
    yield X()
    try:
        if sys.last_value:
            # error
    except AttributeError:
            # no error thrown

def test1(fix):
    some_method_that_might_throw_an_exception()
Run Code Online (Sandbox Code Playgroud)

python testing pytest

1
推荐指数
1
解决办法
3165
查看次数

标签 统计

python ×3

ajax ×1

forms ×1

html ×1

if-statement ×1

indentation ×1

input ×1

nested ×1

pep ×1

php ×1

pytest ×1

subclass ×1

testing ×1

type-hinting ×1