如何在Python中只测试子类方法而不实例化基类?

2024-10-03 15:25:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新手,我需要在不初始化基类实例的情况下测试子类方法,因为在基类中,对网络和其他组件有很多依赖,我的子类方法是 独立的。你知道吗

我试图通过从子类中删除基类方法来创建一个新的子类,但它无法工作。这是密码。你知道吗

def remove_base(child_cls, base_cls):
    allmembers = inspect.getmembers(child_cls, predicate=inspect.ismethod)
    allmembers_dict = dict(allmembers)
    hbasemembers = inspect.getmembers(base_cls, predicate=inspect.ismethod)
    hbase_dict = dict(hbasemembers)
    child_class_member = set(allmembers_dict.keys()) - set(hbase_dict.keys())
    new_dict = {}
    for key in allmembers_dict.keys():
        for child_member in child_class_member:
            if key == child_member:
                new_dict[key] = allmembers_dict[key]
    return new_dict

class A:
    def add(self, i):
        print i + 1

class B(A):
    def sub(self, i):
        print i - 1

newB = type("newB", (object, ), remove_base(B, A))
b = newB()
b.sub(5)

错误消息是:

TypeError: unbound method sub() must be called with B instance as first argument (got int instance instead)

我认为删除基类方法的方法可能是错误的。 如何处理这个问题?你知道吗


Tags: 方法keychildnewbasedefkeys基类
1条回答
网友
1楼 · 发布于 2024-10-03 15:25:54

您可以直接使用来自B__dict__

class A(object):
    def add(self, i):
        print(i + 1)

class B(A):
    def sub(self, i):
        print(i - 1)

newB = type("newB", (object, ), dict(B.__dict__))
b = newB()
b.sub(5)

相关问题 更多 >