小编Mik*_*kay的帖子

Python3 super()和泛型类

我相信一个测试用例胜过千言万语:

#!/usr/bin/env python3

def generate_a(key):
    class A(object):
        def method(self):
            return {'key': key,}
    return A

BaseForB = generate_a(1337)

class B(BaseForB):
    def method(self):
        dict = super(BaseForB, self).method()
        dict.update({'other_key': 0,})
        return dict

EXPECTED = {'other_key': 0, 'key': 1337,}
RESULT = B().method()

if EXPECTED == RESULT:
    print("Ok")
else:
    print("EXPECTED: ", EXPECTED)
    print("RESULT: ", RESULT)
Run Code Online (Sandbox Code Playgroud)

这引起了:

AttributeError: 'super' object has no attribute 'method'
Run Code Online (Sandbox Code Playgroud)

现在的问题是-如何运行A.method()B.method()(我试过做的事情super())

编辑

这是更合适的测试用例:

#!/usr/bin/env python3

def generate_a(key):
    class A(object):
        def method(self):
            return {'key': key,}
    return A …
Run Code Online (Sandbox Code Playgroud)

python super python-3.x

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

检查是否在给定的类中定义或派生了类属性

class A:
    foo = 1

class B:
    foo = 2

class C:
    foo = 3

class D(A, B, C):
    pass

def collect_foo(cls):
    import inspect
    foos = []
    for c in inspect.getmro(cls):
        if hasattr(c, 'foo'):
            foos.append(c.foo)
    return foos
Run Code Online (Sandbox Code Playgroud)

现在collect_foo(D)返回[1, 1, 2, 3]- 1加倍- D从中派生出来A.问题是 - 如何获得独特foo的.我想到的第一件事是检查属性是否在给定的类中派生或声明 - 是否可能?怎么做?

python inheritance python-3.x

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

标签 统计

python ×2

python-3.x ×2

inheritance ×1

super ×1