开发者

Python Cross Module Variables

开发者 https://www.devze.com 2023-02-10 15:05 出处:网络
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 i

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: Name开发者_如何学JAVAResult.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 ...


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
0

精彩评论

暂无评论...
验证码 换一张
取 消