是否可以使用原始对象的属性创建新的Object而无需更改它?
例如 :
public void exampleTests() {
Tree t = Trees.makeTree(new int[]{2, 3, 4, 4, 1});//creating tree
assertTrue(t.contains(4)); //check if 4 is a node
assertFalse(t.contains(6));//check if 6 is a node
assertEquals(4, t.size()); //return size-nodes number (only different digits)
Tree t2 = t.add(6).add(7).add(6); // obj 2 take obj 1 and add 6 and 7 to it
assertFalse(t.contains(6)); // the first object should have no 6
assertTrue(t2.contains(6)); // the second object should have 6
Run Code Online (Sandbox Code Playgroud)
树类:
public class Trees {
public static Tree …Run Code Online (Sandbox Code Playgroud) 是否可以自己创建一个类的新对象(在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 …Run Code Online (Sandbox Code Playgroud)