几句话就能给出答案
在您的示例中,itsProblem 是一个局部变量。
您必须使用self 来设置和获取实例变量。您可以在__init__ 方法中设置它。那么您的代码将是:
class Example(object):
def __init__(self):
self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
但是如果你想要一个真正的类变量,那么直接使用类名:
class Example(object):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)
但要小心这个,因为theExample.itsProblem 自动设置为等于Example.itsProblem,但根本不是同一个变量,可以单独更改。
一些解释
在 Python 中,可以动态创建变量。因此,您可以执行以下操作:
class Example(object):
pass
Example.itsProblem = "problem"
e = Example()
e.itsSecondProblem = "problem"
print Example.itsProblem == e.itsSecondProblem
打印
是的
因此,这正是您对前面的示例所做的。
确实,在 Python 中,我们使用 self 和 this,但不止于此。 self 是任何对象方法的第一个参数,因为第一个参数始终是对象引用。这是自动的,不管你是否称它为self。
这意味着你可以做到:
class Example(object):
def __init__(self):
self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
或:
class Example(object):
def __init__(my_super_self):
my_super_self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
完全一样。 ANY 对象方法的第一个参数是当前对象,我们只是将其称为self 作为约定。 您只需向该对象添加一个变量,就像从外部执行此操作一样。
现在,关于类变量。
当你这样做时:
class Example(object):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
您会注意到我们首先设置一个类变量,然后我们访问一个对象(实例)变量。我们从未设置过这个对象变量,但它可以工作,这怎么可能?
好吧,Python 会尝试首先获取对象变量,但如果找不到它,就会给你类变量。 警告:类变量是实例间共享的,而对象变量不是。
作为结论,永远不要使用类变量来为对象变量设置默认值。为此使用__init__。
最终,您将了解到 Python 类是实例,因此也是对象本身,这为理解上述内容提供了新的见解。一旦你意识到这一点,请稍后再读一遍。