如何在Python中访问类成员变量?

人气:517 发布:2022-10-16 标签: methods python class oop class-variables

问题描述

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 

打印

True

因此,这正是您对前面的示例所做的操作。

确实,在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)

完全一样。任何对象方法的第一个参数都是当前对象,我们仅将其称为self作为约定。您只需向此对象添加一个变量,与从外部添加变量的方式相同。

现在,关于类变量。

当您这样做时:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

您会注意到,我们首先设置一个类变量,然后访问一个对象(实例)变量。我们从未设置过此对象变量,但它可以工作,这怎么可能?

嗯,Python试图首先获取对象变量,但如果它找不到它,就会给您提供类变量。警告:类变量在实例之间共享,而对象变量不共享。

总而言之,永远不要使用类变量来设置对象变量的默认值。为此使用__init__

最终,您将了解到,Python类是实例,因此是对象本身,这为理解上述内容提供了新的见解。一旦你意识到这一点,请稍后再来阅读这篇文章。

574