Python, pass variable into class

Posted on 2009-04-28
Last Modified: 2012-05-06
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 = ''

class Parser(HTMLParser, url):

    print url

hParser = Parser(url)

Open in new window

Question by:ScriberUK
    LVL 41

    Expert Comment

    url = ''

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

    hParser = Parser( url )
    LVL 39

    Accepted Solution

    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
    # This is the HTMLParser.__init__() method:
        def __init__(self):
            """Initialize and reset this instance."""
    # You can do the same from your __init__ method, instead of calling HTMLParser.__init__():
    class Parser(HTMLParser):
        def __init__(self, url):
            self.URL = url

    Open in new window


    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
    Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
    Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
    Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

    732 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now