[英]How can I reference the __init__ method of a derived class in Python from the base class?
[英]How to set the "base class list" in derived class __init__ in Python?
我有一個擴展列表的 class; 盡可能簡化,它看起來像:
class grid(list):
def __init__(self, data):
"If data is an int, create empty grid of size data; if data is a list, initialize grid with that data."
if type(data) == grid: # make a new copy of the old grid instance 'data'
self += data
self.__dict__ |= data.__dict__.copy()
elif type(data) == list:
self += data
self.score = sum(len(row) for row in data)
elif type(data) == int:
self += [[] for _ in range(data)] # NOTE: [[]]*data creates multiple references to the same empty row!
self.score = 0
else: raise Exception("data must be integer or list!")
它有效,但我覺得很尷尬,我必須(?)使用+=
將我想要創建的內容“附加”到最初為空的“基本列表”:如果使用,例如self = data
,那么self
成為一個基本列表並設置諸如“self.score = ...”之類的屬性將導致錯誤。
我認為和/或知道我也可以使用super().__init__(data)
將給定的初始數據復制到基礎列表中。 但它看起來有點矯枉過正,不必要地“沉重”。 (我的做法不是更高效嗎?畢竟,空列表已經存在, super().__init__
創建一個全新的列表嗎?)對於 data=int 的情況,我應該然后說super().__init__([...])
創建新的“空”列表的兩個副本:一個作為參數給 super.init 和由該 function 創建的副本?
另外,我的代碼是否用於創建現有grid
實例的副本,特別是self__dict__ |= data.__dict__.copy()
,是通往 go 的方式? 實際上,除了.score
之外,還有更多屬性,其中一些是列表。 我知道我必須(?)為它們中的每一個使用單獨的copy()
來有效地創建這些的新副本,而不僅僅是對舊實例的屬性的引用。 我應該使用一些deepcopy
模塊以“更清潔”(?)的方式做到這一點嗎?
忽略其他一些問題,我會這樣寫 class :
class grid(list):
def __init__(self, lists: list[list]):
self.extend([x] for x in lists)
@classmethod
def from_grid(cls, g: grid):
# A grid is already a list of lists
return cls(g)
@classmethod
def from_int(cls, n):
return cls([[] for _ in range(n)])
像list([1,2,3])
這樣的調用首先使用list.__new__
創建一個空列表(忽略參數,盡管可能使用它為新列表預分配足夠的空間以容納三個值),然后傳遞新的list 和給定的 iterable 到list.__init__
將值從 iterable 復制到新列表中。 您可以通過覆蓋__init__
來檢查self
在調用super().__init__
之前和之后的值來看到這一點:
class A(list):
def __init__(self, x):
print(self)
super().__init__(x)
print(self)
然后
>>> a = A([1,2,3])
[]
[1, 2, 3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.