1

I realize there are other threads addressing this problem but as I am fairly new to 'Classes' and have already constructed my class structure ... I would like to find a method that I can integrate into my code. I'm sure this will NOT be a difficult one to answer!

First File: NameResult.py

from NameAssign import *

NameList = NameWorks()
print(NameList.InputNames(NameVar))

Second File: NameAssign.py

class NameWorks:
    def __init__(self, NameVar = []):

        self.NameVar = NameVar

    def InputNames(self, NameVar):
        global NameVar
        NameVar = ['harry', 'betty', 'sam']

Result:

NameError: name 'NameVar' is not defined

All replies are much appreciated ...

1
  • 1
    If Ignacio's answer works for you, you should accept it. Commented Jan 10, 2012 at 3:06

1 Answer 1

4

NameVar is not defined in NameAssign; it only exists within NameAssign.NameWorks.InputNames() as a local variable. The easiest way to fix this is to define it in NameAssign at the global level.

Edit:

It turns out that this is what you want to do:

NameResult.py

import NameAssign

namelist = NameAssign.NameWorks(['harry', 'betty', 'sam'])
print namelist.InputNames()  # or print(...) for Py3k

NameAssign.py

class NameWorks(object):
  def __init__(self, names):
    self.names = names

  def InputNames(self):
    return self.names
Sign up to request clarification or add additional context in comments.

12 Comments

great, where/how do I define it as global. I've tried placing 'global NameVar' all over the place and it just returns: SyntaxError: name 'NameVar' is parameter and global
Not "as global", at the global level, i.e. at the same level as NameWorks.
This might be where the 'I'm new to classes' comes in. Could I have like an line or two of code as an example
This has nothing to do with classes. NameVar = ['harry', 'betty', 'sam']
oh ok. i see. I would like to record three names inside a list variable inside of class: NameWorks and import that list variable into NameResult.py
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.