我对Python中的包装类一无所知。我试图在一个使用多个链表的链表程序中实现它。我的代码是:
def nodewrap(cls):
class Nodewrap:
def __init__(self):
self.head = None
self.tail = None
return Nodewrap
@nodewrap
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Intersection:
def addnode(self,d):
newnode = Node(d)
if head == None:
head = tail = newnode
else:
tail.next = newnode
tail = newnode
obj1 = Intersection()
obj2 = Intersection()
obj3 = Intersection()
s1 = int(input("Enter size of 1st list : n"))
for i in range(s1):
obj1.addnode(int(input("Enter the data : n")))
s2 = int(input("Enter size of 1st list : n"))
for i in range(s2):
obj2.addnode(int(input("Enter the data : n")))
temp1 = obj1.head
for i in range(s1):
temp2 = obj2.head
for j in range(s2):
if temp1.data == temp2.data:
obj3.addnode(temp1.data)
break
temp2 = temp2.next
temp1 = temp1.next
print("Intersection is :")
temp = obj3.head
while temp!=None:
print(temp.data,end=" ")
temp = temp.next
我想使用包装器类来包装类Node,而不是使用交集类的对象,只将数据字段作为头、尾。但它给了我一些关于init((的错误。
请帮忙。
我试着从这里学到:https://www.geeksforgeeks.org/wrapper-class-in-python/
我想我理解你想做什么,但我认为你不想使用装饰器,但你想从NodeWrap
类继承
class Nodewrap:
head = None
tail = None
class Node(NodeWrap):
def __init__(self,data):
self.data = data
self.next = None
但我看不出有什么理由以这种方式继承。对于一个链表来说,这应该足够了。我添加了is_first
和is_last
属性
from __future__ import annotations
class Node:
prev_node = None
next_node = None
def __init__(self, data):
self.data = data
def add_node(self, node: Node) -> None:
if self.prev_node is not None:
raise ValueError('Previous node already defined.')
self.next_node = node
node.prev_node = self
@property
def is_first(self) -> bool:
return self.prev_node is None
@property
def is_last(self) -> bool:
return self.next_node is None
您可以实现next,iter并创建一个Iterator类。
我不建议使用next
作为变量名。此处引用from __future__ import annotations
。它只是用于自我参考注释。