0

I have this class

class SECHeader(object):
    def __init__(self,header_path):
        self.header = open(header_path).read()

I have some methods in this class, one of the methods I am trying to do needs to parse the name

        def parsed_name(self):
            return header_path.split('-')[-1]

This works fine if in my code I use the name header_path to identify the thing I am trying to operate on

for header_path in header_paths:
       header = SECHeader(header_path)
       print header.parsed_name()

But if I change the name

for named_path in header_paths:
       header = SECHeader(named_path)
       print header.parsed_name()

I get a NameError

I played around - if can use any name for the object in the parsed_name function as long as I use the same name for the object I want to process but I can't seem to figure out how to name it so a user does not have to use my naming scheme

specifically if I change the parsed_name function to

        def parsed_name(self):
            return banana.split('-')[-1]

and in my loop if change it to

for banana in header_paths:
    header = SECHeader(banana)
    print header.parsed_name()

it works like a charm but that limits the portability of this thing I am working on. as any user would have to reference the path with whatever label I use in the function.

PyNEwbie
  • 4,882
  • 4
  • 38
  • 86

1 Answers1

1

The problem here is that you have header_path declared as a variable for the init function. It's scope is local to the init function.

What you need is to associate header_path as a variable for the class instance.

Class SECHeader(object):
    def __init__(self,header_path):
        self.header_path = header_path # Instantiate a variable for class object
        self.header = open(header_path).read()

    def parsed_name(self):
        return self.header_path.split('-')[-1] # Call the associated variable

Another way is to actually call the variable that you gave as an argument to SECHeader in parsed_name. This variable name would be in the class namespace.

for banana in header_paths:
    header = SECHeader(banana)
    print header.parsed_name()

Class SECHeader(object):
    def __init__(self,header_path): # header_path takes value of banana
                                    # and ends scope in __init__
        self.header = open(header_path).read()

    def parsed_name(self):
        return banana.split('-')[-1] # banana was passed to class and is known
Nitin
  • 2,624
  • 7
  • 29
  • 43