gpt4 book ai didi

python - 是否允许在抽象类中使用用户定义的装饰器?或者说,应该继承后使用吗?

转载 作者:行者123 更新时间:2023-12-01 00:50:01 25 4
gpt4 key购买 nike

例如,假设我定义了一个装饰器,名为:decorate

def decorate(func):
def inside_func(*args, **kwargs):
# Do something
return func(*args, **kwargs)
return inside_func

接下来,假设我正在编写一个名为 Model 的抽象类

from abc import ABC, abstractmethod

class Model(ABC):
def __init__(self, value):
self.value = value
super().__init__()

@abstractmethod
@decorate # <-------------------- IS @decorate ALLOWED HERE?
def do_something(self):
pass

或者,应该是:

from abc import ABC, abstractmethod

class Model(ABC):
def __init__(self, value):
self.value = value
super().__init__()

@abstractmethod
def do_something(self):
pass

# Inherit the base class
class DoAdd42(Model):
@decorate # <----------------------- SHOULD @decorate BE HERE INSTEAD?
def do_something(self):
return self.value + 42

如果两者都允许,是否有“最佳实践”方法来做到这一点?

最佳答案

两者都允许。因为abstractmethod,你的类中的decoratesomething都是函数。您可以将它们打印到控制台进行验证。

In [2]: def decorate(func):
...: def inside_func(*args, **kwargs):
...: # Do something
...: return func(*args, **kwargs)
...: return inside_func
...:
In [7]: from abc import ABC, abstractmethod
...:
...: class Model(ABC):
...: def __init__(self, value):
...: self.value = value
...: super().__init__()
...:
...: @abstractmethod
...: @decorate # <-------------------- IS @decorate ALLOWED HERE?
...: def do_something(self):
...: pass
...: # even no self is valid for class in Python3+
...: def whatever():
...: print('fff')
...:

In [8]: print(abstractmethod)
<function abstractmethod at 0x100ff86a8>

In [9]: print(Model.do_something)
<function decorate.<locals>.inside_func at 0x1041031e0>

In [10]: print(Model.whatever)
<function Model.whatever at 0x103b48950>

In [11]: Model.whatever()
fff

我不熟悉abstractmethod,因此我不知道最佳实践以及有关其规则的更多详细信息。你可以根据我给你的信息,结合你自己对abstractmethod的理解,尝试做出自己的判断。

关于python - 是否允许在抽象类中使用用户定义的装饰器?或者说,应该继承后使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56639879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com