在Python中访问类的成员变量?
问题内容:
class Example(object):
def the_example(self):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
如何访问类的变量?我尝试添加此定义:
def return_itsProblem(self):
return itsProblem
但是,这也失败了。
问题答案:
简而言之,答案
在您的示例中,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
as
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类是实例,因此是对象本身,这为理解上述内容提供了新的见解。一旦意识到这一点,请稍后再阅读。