是否有可能在类中创建一个类的新对象(在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) + "]"
答案 0 :(得分:5)
是否有可能在类中创建一个类的新对象(在python中)?
是。这完全有可能。
以下是一个例子:
>>> class A:
def __init__(self, value):
self.value = value
def make_a(self, value):
return A(value)
def __repr__(self):
return 'A({})'.format(self.value)
>>> a = A(10)
>>> a.make_a(15)
A(15)
>>>
现在你可能在想,“但是A
类尚未定义。为什么Python不会引发NameError
?”这个原因因为Python执行代码的方式而起作用。
当Python创建A
类,特别是make_a
方法时,它会看到正在调用标识符A
。它不知道A
是函数还是类,或者A
是定义的。但它不需要知道。
在运行时确定A
的确切含义。这是Python唯一一次检查A
是否 定义的。
这也是您能够编译引用未定义变量的函数的原因:
>>> def foo():
a + b
>>> foo # Python compiled foo...
<function foo at 0x7fb5d0500f28>
>>> foo() # but we can't call it.
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
foo() # but we can't call it.
File "<pyshell#7>", line 2, in foo
a + b
NameError: name 'a' is not defined
>>>
答案 1 :(得分:1)
看起来像一个双端队列(双端队列)并且切片操作不会退出。您需要在l1之前修复项目上的prev / next链接,并在l2之后修复该链接。
def slice(self, l1, l2):
new = LinkedList()
new.first = l1
new.last = l2
if l1.prev:
l1.prev.next = l2.next
if l2.next:
l2.next.prev = l1.prev
l1.prev = l2.next = None
return new