gpt4 book ai didi

Python函数不访问类变量

转载 作者:太空狗 更新时间:2023-10-30 00:20:46 25 4
gpt4 key购买 nike

我试图在外部函数中访问类变量,但是我得到了 AttributeError,“类没有属性”我的代码看起来像这样:

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

def notaclass():
print example.somevariable

AttributeError: class example has no attribute 'somevariable'

其他问题也被问到与此类似,但所有答案都说在 init 期间使用 self 和 define ,我做到了。为什么我不能访问这个变量。

最佳答案

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

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函数不访问类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16680221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com