在Python中访问类的成员变量?

在Python中访问类的成员变量?,第1张

在Python中访问类的成员变量

简而言之,答案

在您的示例中,

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):    passExample.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类是实例,因此是对象本身,这为理解上述内容提供了新的见解。一旦意识到这一点,请稍后再阅读。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/5648403.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存