簡體   English   中英

Python:如何使用 __len__() 返回作為參數傳遞給 class 的列表長度

[英]Python: how to return the length of the list passed to class as an argument with __len__()

在以下代碼中,class 獲取一個列表作為參數。 Object 有一個“長度”變量(該列表的長度)

__ len __() 方法必須返回“length”的值

class Gen:
    def __init__(self, lst, length ):
        self.lst = lst  # list
        self.length = length

    def show(self):
        print("List:", self.lst)

    def __len__(self):
        # will return 'length's value
        pass

x = Gen([1, 2, 3, 4])
x.show()

您可以使用“self”訪問屬性“lst”的長度。 此外,由於長度基於您的屬性,您可以將其定義為屬性(或者甚至不聲明它......):

class Gen:
  def __init__(self, lst):
    self.lst = lst  # list

  def show(self):
    print("List:", self.lst)

  def __len__(self):
    return len(self.lst)

x = Gen([1, 2, 3, 4])
x.show()
print(len(x)) # print 4

如果您仍然想使用長度變量,那么您可以這樣做:

class Gen:
  def __init__(self, lst):
    self.lst = lst  # list
    self.length = len(lst)

  def show(self):
    print("List:", self.lst)

  def __len__(self):
    return len(self.length)

x = Gen([1, 2, 3, 4])
x.show()
print(len(x)) # print 4 

請注意,當您更新 lst 時,屬性長度不會更新。

如果您仍然想要一個長度屬性(感覺 javaey,因為在 python 中您使用 len),那么您可以這樣做:

class Gen:
  def __init__(self, lst):
    self.lst = lst  # list

  @property
  def length(self):
    return len(self.lst)

  def show(self):
    print("List:", self.lst)

  def __len__(self):
    return len(self.length)

x = Gen([1, 2, 3, 4])
x.show()
print(len(x)) # print 4 

無論如何,您的問題有很多變體。

我想你想要這樣的東西 -

class Gen:
    def __init__(self, lst):
        self.lst = lst  # list
        self.length = len(self.lst)

    def show(self):
        print("List:", self.lst)
        print("List Length:", self.length)

    def __len__(self):
        # will return 'length's value
        return self.length;

x = Gen([1, 2, 3, 4])
x.show()

暫無
暫無

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

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