Python函数无法访问类变量

发布于 2021-01-29 15:20:32

我正在尝试在外部函数中访问类变量,但是出现AttributeError,“类没有属性”,我的代码如下所示:

class example():
     def __init__():
          self.somevariable = raw_input("Input something: ")

def notaclass():
    print example.somevariable

AttributeError: class example has no attribute 'somevariable'

有人问过与此类似的其他问题,但是所有答案都说要使用self并在 init 期间定义,这就是我所做的。为什么我不能访问此变量。

关注者
0
被浏览
151
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果要创建类变量,则必须在任何类方法之外(但仍在类定义之内)声明它:

    class Example(object):
          somevariable = 'class variable'
    

    现在,您可以访问您的类变量。

    >> Example.somevariable
    'class variable'
    

    您的示例无法正常运行的原因是因为您正在为instance变量分配值。

    两者之间的区别在于class,一旦创建了类对象,便会立即创建一个变量。而instance一旦 实例化
    对象并且仅在将它们分配给对象之后,将创建一个变量。

    class Example(object):
          def doSomething(self):
              self.othervariable = 'instance variable'
    
    >> foo = Example()
    

    在这里,我们创建了的实例Example,但是如果尝试访问othervariable,则会收到错误消息:

    >> foo.othervariable
    AttributeError: 'Example' object has no attribute 'othervariable'
    

    由于othervariable在内部分配doSomething-我们还没有称为ityet-,因此不存在。

    >> foo.doSomething()
    >> foo.othervariable
    'instance variable'
    

    __init__ 是一种特殊的方法,只要发生类实例化,该方法就会自动被调用。

    class Example(object):
    
          def __init__(self):
              self.othervariable = 'instance variable'
    
    >> foo = Example()
    >> foo.othervariable
    'instance variable'
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看