Python, pass variable into class

Hello all,

I have a class which I define thus: "class Parser(HTMLParser):". I would now like to pass a variable into it as per the pseudocode below but I get the following error "NameError: name 'url' is not defined"

Help :)
url = 'www.test.com'
 
class Parser(HTMLParser, url):
    print url
 
hParser = Parser(url)

Open in new window

ScriberUKAsked:
Who is Participating?
 
Roger BaklundConnect With a Mentor Commented:
The Parser class is defined as a sub-class of HTMLParser. When overriding the constructor (__init__ method), you must remember to also call the parent constructor, or execute the equivalent code, or you will get errors. In this case you get this error:

AttributeError: Parser instance has no attribute 'rawdata'

There are two possible ways to do it:
# The standard way of doing it:
class Parser(HTMLParser):
    def __init__(self, url):
        self.URL = url
        HTMLParser.__init__(self)
 
# This is the HTMLParser.__init__() method:
 
    def __init__(self):
        """Initialize and reset this instance."""
        self.reset()
 
# You can do the same from your __init__ method, instead of calling HTMLParser.__init__():
 
class Parser(HTMLParser):
    def __init__(self, url):
        self.URL = url
        self.reset()

Open in new window

0
 
HonorGodSoftware EngineerCommented:
url = 'www.test.com'

class Parser( HTMLParser ) :
  def __init__( self, url ) :
    self.URL = url

hParser = Parser( url )
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.