Problem
I am working with class objects in a single linked list. It could be nice to have a method that returns the specific variables requested. Is this possible?
So far I am having a method under the Linked List class:
Works
class SLinkedList:
def __init__(self):
self.headval = None
def getListZ(self,):
val = self.headval
arr = []
while val is not None:
arr.append(val.val.Z)
val = val.nextval
return arr
Wants:
class SLinkedList:
def __init__(self):
self.headval = None
def getListZ(self,var):
item = self.headval
arr = []
while val is not None:
arr.append(item.val.var)
item = item.nextval
return arr
Questions
- How can I write a method that returns a list of certain variables from the class objects? Let's say that I want to return a list of all the impedances. How would I do that?
Workaround
I can get a list for any desired variable (in the example, the list is called from another class):
vals1 = [item.val.val1 for item in self.list]
Iteration is possible with the following method:
def __iter__(self):
node = self.headval
while node:
yield node
node = node.nextval
However
I would still be able to dynamically print several variables from my object in a linked list. How can I make this a variable instead of hard-coding this as I have done below?
Code
Script
class Node:
def __init__(self, val=None):
self.val = val
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
def __iter__(self):
node = self.headval
while node:
yield node
node = node.nextval
# Function to add newnode
def AtEnd(self, newdata):
NewNode = Node(newdata)
if self.headval is None:
self.headval = NewNode
return
laste = self.headval
while(laste.nextval):
laste = laste.nextval
laste.nextval=NewNode
# Print the linked list
def listprint(self,):
printval = self.headval
while printval is not None:
try:
print (printval.val.nodes,printval.val.Ctype,printval.val.Z,sep='\t')
except:
print (printval.val.nodes,printval.val.Ctype,sep='\t')
printval = printval.nextval