您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python函数无法访问类变量

Python函数无法访问类变量

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

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'
python 2022/1/1 18:37:39 有250人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶