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

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

在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):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem

版画

真正

因此,这正是您使用前面的示例所做的。

的确,在Python中我们使用selfasthis,但还不止于此。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类是实例,因此是对象本身,这为理解上述内容提供了新的见解。一旦意识到这一点,请稍后再阅读。

python 2022/1/1 18:51:34 有401人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

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

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

请先登录

推荐问题


联系我
置顶