是否有可能創建一個類的新對象本身(在Python中)?在python的同一個類中創建一個類的新對象?
爲了解釋這個想法更多我寫這段代碼,我不認爲它的作品。
新的對象應該是從當前對象(新的屬性等)
class LinkedList:
def __init__(self):
""" Construct an empty linked list. """
self.first = None
self.last = None
def insert_before(self, new_item, next_item):
""" Insert new_item before next_item. If next_item is None, insert
new_item at the end of the list. """
# First set the (two) new prev pointers (including possibly last).
if next_item is not None:
new_item.prev = next_item.prev
next_item.prev = new_item
else:
new_item.prev = self.last
self.last = new_item
# Then set the (two) new next pointers (including possibly first).
if new_item.prev is not None:
new_item.next = next_item
new_item.prev.next = new_item
else:
new_item.next = self.first
self.first = new_item
# assuming l1, l2 obj of class node with prev and next (attributes)
def slice(self, l1, l2):
curr = l1
new = LinkedList()
new.first = l1
new.last = l2
if l1.prev is not None:
l2.prev = l1.prev
else:
self.first = l2.next
self.first.prev = None
if l2.next is not None:
l1.next = l2.next
else:
self.last = l2.next
Return new
class Node:
def __init__(self, value):
""" Construct an item with given value. Also have an id for each item,
so that we can simply show pointers as ids. """
Node.num_items += 1
self.id = Node.num_items
self.prev = None
self.next = None
self.value = value
def __repr__(self):
""" Item as human-readable string. In Java or C++, use a function like
toString(). """
return "[id = #" + str(self.id) \
+ ", prev = #" + str(0 if self.prev is None else self.prev.id) \
+ ", next = #" + str(0 if self.next is None else self.next.id) \
+ ", val = " + str(self.value) + "]"
你呈現不創建test'的'一個完全獨立的實例代碼。雖然這個例子有點沒有意義,因爲'test'沒有任何屬性。你爲什麼認爲它不起作用?你打算用'new'做什麼? (順便說一下,你的'__init__'有語法錯誤。) – 5gon12eder
你的代碼工作正常。你試過了嗎? –
@ 5gon12eder,因爲我試着在一個真實的代碼,並試圖改變屬性值,並沒有工作 – james