Skip to main content
 首页 » 编程设计

Python之在子类方法定义中指定精确参数

2024年10月24日11mate10pro

在 Python 中是否有任何方法可以在父类方法中指定可变(未知)数量的参数,并在其子类中指定实际(实际)参数而不会收到警告?这是一个让我理解的例子(我使用的是 Python 3.5):

import abc 
 
class SuperClass(metaclass=abc.ABCMeta): 
    @abc.abstractmethod 
    def method(self, *args): 
 
class SubClass1(SuperClass): 
    def method(self, one, two, three):  # <-- I get a warning here 
        # Stuff 
 
class SubClass2(SuperClass): 
    def method(self, *args): 
        # Stuff 

我不知道如何让这段代码没有警告。我得到的警告是:

Signature of method 'SubClass1.method() does not match signature of base method in class 'SuperClass' 

已更新

我只在我的 IDE Pycharm 4.5 中收到警告,这是由检查 Python->“Class must implement all abstract methods”造成的。

请您参考如下方法:

您可以在子类中尝试这样做:

class SubClass1(SuperClass): 
    def method(self, *args): 
        try: 
            one, two, three = args 
        except ValueError: 
            print('bad number of args') 

话虽如此,如果您希望在您的 IDE 中使用代码完成功能,这可能无济于事。