簡體   English   中英

如何在裝飾器中使用`@dataclass` 裝飾器?

[英]How to use `@dataclass` decorator within a decorator?

我想創建一個 class 裝飾器來預定義一些屬性和方法來裝飾 class。 同時,我希望這個裝飾的 class 用@dataclass裝飾器裝飾。 為了讓用戶更輕松,我希望用戶只需使用我的裝飾器,以便他/她的 class 用@dataclass裝飾。

所以這里是我想出的裝飾一個 class 的方法,這樣被裝飾的 class 就有一個新的屬性id_ 我正在提交此代碼以了解 decoartor 的嵌套是否“可接受”? 基本上,我不太確定調用像 function 這樣的裝飾器(雖然它是一個函數),所以我想知道是否會有副作用?

from dataclasses import dataclass

# My library: complexitiy is allowed.
def indexer(orig_class):
    orig_class = dataclass(orig_class)
    # Copy of original __init__ to call it without recursion.
    orig_init = orig_class.__init__
    id_ = 10

    def __init__(self,*args, **kws):
        self.id_ = id_
        orig_init(self, *args, **kws) # Call the original __init__

    orig_class.__init__ = __init__ # Set the class' __init__ to the new one

    return orig_class

# User environment: importing @indexer decorator: ease of use is targeted.
# Expected behavior is that @indexer provides same functions as @dataclass.
@indexer
class Truc:
    mu : int

# Test
test = Truc(3)

test.mu
Out[37]: 3

test.id_
Out[38]: 10

作為旁注,我不知道裝飾器是否比 class inheritance 更好,在添加屬性和方法時? 感謝您的建議,Bests,

基本上,我不太確定調用像 function 這樣的裝飾器(雖然它是一個函數),所以我想知道是否會有副作用?

python中的裝飾器語法糖動機中的PEP 318給出了以下示例

def foo(cls):
    pass
foo = synchronized(lock)(foo)
foo = classmethod(foo)

相當於

@classmethod
@synchronized(lock)
def foo(cls):
    pass

換句話說,裝飾器允許您編寫更少的代碼行以獲得完全相同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM