簡體   English   中英

在python中繼承元組 - 有序元組

[英]Inherit Tuple in python - ordered tuple

我想創建一個類:

  • 具有與tuple相同的行為:
    • 不可變元素
    • 有方法__len__index__getitem__等等
  • 元組只有floats並且是有序的
  • 有一個屬性qtmin計算有多少元素等於最小值

所以,我的想法是繼承tuple的類。

class MyTuple(tuple):
    @staticmethod
    def VerifyIsOrdered(U: tuple[float]):
        n = len(U)
        for i in range(n-1):
            if U[i] > U[i+1]:
                raise ValueError("U must be ordered")

    def __init__(self, U: tuple[float]):
        MyTuple.VerifyIsOrdered(U)
        super().__init__(U)

    @property
    def qtmin(self):
        minU = min(self)
        for i in range(len(self)):
            if self[i] != minU:
                return i
    
MyTuple([0, 1, 2, 3])  # qtmin = 1
MyTuple([0, 0, 0, 1, 2, 3])  # qtmin = 3

但是我在super().__init__(U)行收到以下錯誤

TypeError: object.__init__() takes exactly one argument (the instance to initialize)

但我不明白有什么問題,因為當我調用super時,它意味着初始化原始tuple 我該如何解決?

tuple是不可變的,因此您需要使用__new__而不是__init__ 文檔

new () 主要是為了允許不可變類型(如 int、str 或 tuple)的子類自定義實例創建。 它也通常在自定義元類中被覆蓋,以自定義類創建。

def __new__(cls, U: tuple[float]):
    MyTuple.VerifyIsOrdered(U)
    return super(MyTuple, cls).__new__(cls, tuple(U))

為了獲得更好的語法,您可以像這樣使用解包:

def __new__(cls,*U):
        MyTuple.VerifyIsOrdered(U)
        return super(MyTuple,cls).__new__(cls,U)

所以你可以寫:

MyTuple(0, 1, 2, 3)

代替

MyTuple([0, 1, 2, 3])

暫無
暫無

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

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