【问题标题】:Why can't I reference a global variable defined in a class? [duplicate]为什么我不能引用类中定义的全局变量? [复制]
【发布时间】:2019-11-09 14:05:30
【问题描述】:
class MyClass(object):
   code_mapping = {...}

 def get_name(code):

    code = code_mapping[code]
    ...

在这段代码中,它抱怨“未定义代码映射”。不是 MyClass 中的所有东西都可以访问 code_mapping 吗?

【问题讨论】:

  • 它可用,但只能通过类或自身。
  • 本周矛盾论:“类中定义的全局变量”。

标签: python


【解决方案1】:

self 初始化它。这将使类中的任何函数都可以访问它,方法是使用 self.<variable> 传递它,然后将 self 作为函数参数传递给您想要将变量传递给的任何对象。

class MyClass(object):
    def __init__(self):
        self.code_mapping = {...} # if this will be a hard coded 

    def get_name(self):

        code = self.code_mapping[code]
        ...

或者你可以这样做:

class MyClass(object):
    def __init__(self, code_mapping):
        self.code_mapping = code_mapping

    def get_name(self):

        code = self.code_mapping[code]
        ...

如果您想在实例化时将一些代码映射作为参数传递给您的类。

要从这里创建一个你想要{'code1' : 'name'} 的类对象,然后像这样启动一个类对象:

code1 = MyClass({'code1' : 'name'})

然后{'code1' : 'name'} 将成为get_name() 所做的任何事情,get_name 中的code 的值将是name

【讨论】:

  • 把它放在构造函数中......
  • 构造函数是必需的还是可选的?
  • 您是否每次都将新参数传递给self.code_mapping,或者这将是一个硬编码变量
  • self.code_mapping[name],其中 'name' 是一个变量。
  • @ling 技术上不需要,但很好的做法。这也是创建新类时将变量传递给类的方式。
猜你喜欢
  • 2015-08-08
  • 2021-01-14
  • 2019-05-04
  • 1970-01-01
  • 2014-01-25
  • 2016-10-07
  • 1970-01-01
  • 2021-06-20
相关资源
最近更新 更多