I've managed to do almost no OOP since I've been using python and I'm trying to get familiar with writing classes and so on.
How can I break the following class into one other function. I'd like to rather than pass two arguments to the class pass the fname first and then call a method called display for all of the xml stuff that I want to print. When I attempted to do that I ended up with Global name issues with tree.
import sys
class Parser(object):
def __init__(self, file_name, mylist):
import xml.etree.ElementTree as etree
self.file_name = file_name
tree = etree.parse(self.file_name)
for node in tree.getiterator():
for element in mylist:
if element in node.tag:
print(node.tag)
list2 = ['KeyId','X509SerialNumber','CompositionPlaylistId']
fname = sys.argv[1]
myfileinstance =Parser(fname,list2)
1 Answer 1
Just make a new method to do what you want that method to do (of course I'm kind of guessing, since you haven't actually shown us the code that is more like what you wanted...). Your __init__ method should only contain logic that is necessary for creation of the object--usually this means assigning instance variables and so on.
import sys
import xml.etree.ElementTree as etree # All imports at the top of the file!
class Parser(object):
def __init__(self, file_name):
self.file_name = file_name
def display(self, rename_this_variable):
tree = etree.parse(self.file_name)
for node in tree.getiterator():
for element in rename_this_variable:
if element in node.tag:
print(node.tag)
list2 = ['KeyId','X509SerialNumber','CompositionPlaylistId']
# Worth a mention: rename this to something that's actually meaningful!
fname = sys.argv[1]
instance = Parser(fname)
instance.display(list2)
__init__? Unless there's a very good reason for doing something else, all your imports should be at the top of the file.__init__()be justself.file_name = file_nameand create a new method whose body is the rest of that code.