相关疑难解决方法(0)

__abstractmethods__和AttributeError

dir()当我注意到这个时,我正在使用内置函数:

>>> dir(type)
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__instancecheck__', '__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__', '__weakrefoffset__', 'mro']
>>> type.__abstractmethods__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __abstractmethods__
>>> list.__abstractmethods__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __abstractmethods__
Run Code Online (Sandbox Code Playgroud)

我不明白,它出现在列表中,为什么我会收到这样的错误?

python python-3.x

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

有没有办法在继承期间持久化装饰器?

我正在尝试使用未实现的方法编写一个抽象类,这将强制继承子级在重写方法(在装饰器中定义)时返回特定类型的值。

当我使用下面显示的代码时,子方法不会调用装饰器。我认为这是因为该方法被覆盖,这很有意义。我的问题基本上是这样的:有没有办法通过方法覆盖使装饰器持久化?

我不反对使用装饰器以外的东西,但这是一个很快想到的解决方案,我很想知道是否有任何方法可以使它起作用。

如果使用装饰器是正确且可能的选择,它看起来像这样:

def decorator(returntype):
    def real_decorator(function):
        def wrapper(*args, **kwargs):
            result = function(*args, **kwargs)
            if not type(result) == returntype:
                raise TypeError("Method must return {0}".format(returntype))
            else:
                return result
        return wrapper
    return real_decorator
Run Code Online (Sandbox Code Playgroud)

我需要我的父类看起来类似于这个:

class Parent(ABC):
    @decorator(int)
    @abstractmethod
    def aye(self, a):
        raise NotImplementedError
Run Code Online (Sandbox Code Playgroud)

子类会做这样的事情:

class Child(Parent):
    def aye(self, a):
        return a
Run Code Online (Sandbox Code Playgroud)

如果需要,我很乐意更好地澄清我的问题,并感谢所有花时间提前阅读此问题的人!

python python-3.x python-decorators

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

标签 统计

python ×2

python-3.x ×2

python-decorators ×1