jam*_*mes -1 python oop linked-list
是否可以自己创建一个类的新对象(在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) + "]"
Run Code Online (Sandbox Code Playgroud)
是否可以自己创建一个类的新对象(在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)
>>>
Run Code Online (Sandbox Code Playgroud)
现在您可能在想:“但是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
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1728 次 |
| 最近记录: |