Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 535
  • Last Modified:

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

0
ScriberUK
Asked:
ScriberUK
1 Solution
 
HonorGodCommented:
url = 'www.test.com'

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

hParser = Parser( url )
0
 
Roger BaklundCommented:
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

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now